Reputation:
I have a simple web api created in C# which a method that returns a string
public string Get()
{
return "Welcome Web API online";
}
I am now calling it via javascript, It successfully hit the doe however it won't return any data, it always falls to error function,
var url = "https://localhost:44381/api/accounts";
$.ajax({
type: 'GET',
dataType: 'json',
url: url,
success: function (data) {
console.log(data);
},
error: function (data) { console.log(data); }
});
Checking the console log, it shows:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:44381/api/accounts?
Please enlighten me.
Upvotes: 0
Views: 49
Reputation: 987
When we use Ajax, angular etc to access a URL that has different origin then CORS (Cross-origin-request-sharing) needs to be handled at different origin side. Past below code in your web api project. In Global.asax.cs file
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
My be helpful to you.It works for me.
Upvotes: 2