Pradeep Yadav

Pradeep Yadav

  • 320
  • 5.7k
  • 2.7m

Access to XMLHttpRequest has been blocked by CORS policy

Nov 16 2018 4:36 AM
Hi,
 
I have created Web Api and trying to access it from MVC application,
 
Now Web Api is having below method
 
[HttpGet]
[Route("api/UserMasterApi/GetUser")]
[EnableCors("*", "*", "*")]
public HttpResponseMessage GetUser(string userName, string userPassword)
{
HttpResponseMessage responseMsg = new HttpResponseMessage();
var user = new UserMastersDBRepository().GetUser(
new UsersMasterBusinessModel()
{
UserName = userName,
UserPassword = userPassword
}
);
if (user == null)
{
return
responseMsg =
Request.CreateResponse(HttpStatusCode.OK,
new
{
Status = "Fail",
Message = "Get Api",
Body = new { Username = "" }
});
}
else
{
return
responseMsg =
Request.CreateResponse(HttpStatusCode.OK,
new
{
Status = "SUCESS",
Message = "Get Api",
Body = new { Username = user }
});
}
}
 
Now when I am trying to access this using ajax call
 
$.ajax({
//url: 'http://localhost:64995/api/UserMasterApi/',
url: 'http://localhost:64995/api/UserMasterApi/GetUser/',
contentType: 'application/json',
// dataType: 'json',
accepts: "application/json; charset=utf-8",
type: 'POST',
data: JSON.stringify({ userName: userName, userPassword: password }),
success: function (data) {
debugger
if (data.Success) {
window.location.href = loc + "/Home";
}
});
 
And in WebApiConfig
 
public static void Register(HttpConfiguration config)
{
config.EnableCors();
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
 
Getting error for CORS.
Please help.

Answers (3)