For reference I'm using Windows 10 and Visual Studio 2017.
I have an MVC web api and corresponding web application complete with login capabilities. I'm simply attempting to debug using IE. Whenever I use a GET call I'm met with the following error: SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied. I have CORS configured and enabled so I'm at a complete loss as to why this isn't working.
In my WebApiConfig file I have this:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.EnableCors();
}
And then in the Web.config file I have this:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:53942" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
The call itself is being made using this code:
var returnValue = [];
console.log(localStorage.getItem('accessToken'));
jQuery.support.cors = true;
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", 'http://localhost:60690/api/ProfilePicture?Username=' + username, false);
xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('accessToken'));
xmlhttp.send();
if (xmlhttp.status == 200) {
returnValue = jQuery.parseJSON(xmlhttp.responseText);
}
}
return returnValue;
Again, I'm just trying to debug. When the projects are deployed they're going to be on the same domain so CORS is irrelevant. What am I missing?
Alright, I finally figured this out. Here's what I did:
Found this other StackOverflow question: CORS on OWIN and accessing /token causes 'Access-Control-Allow-Origin' error. Ironically the answer with the most downvotes was the one that helped me the most. I added in the following line into the GrantResourceOwnerCredentials class:
context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
Go into each controller and add the following line at the top:
[EnableCors(origins: "http://localhost:53942", headers: "", methods: "", SupportsCredentials = true)]
Once I did this it started working.
User contributions licensed under CC BY-SA 3.0