I have been banging my head against the wall trying to fix this issue for a week. Hopefully someone can see something I am missing.
I have two projects: localhost:A
(Web-Api) hosts a js file and localhost:B
(.NET MVC) uses that js file. When attempting to capture an error in the js file and send it to localhost:A
I get a cryptic Script Error
message instead of the actual error.
A quick google search tells me this is an security measure that prevents localhost:A
from gathering information about the client. To solve this I need to do two things:
- add
crossorigin='anonymous'
the thelocalhost:B
's reference to the js file - add the HttpHeader
Access-Control-Allow-Origin="*"
to the js file response.
I have found several ways to do 2. on Web-Api, but none seem to work.
I have tried adding the header in the Web.config file like this:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
</customHeaders>
<httpProtocol>
I have tried adding the header in the Global.asax.cs file like this:
public static void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(corsAttr);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
I have tried adding the header in the Startup.cs file like this:
public void Configuration(IAppBuilder app)
{
//app.UseCors(CorsOptions.AllowAll);<--and here
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true
};
map.RunSignalR(hubConfiguration);
});
}
HTTP and SignalR transmissions are occurring with the header, but the files that are being fetched are missing the header.
What am I missing?
EDIT: Here is a screenshot of the current Request and Response headers:
EDIT 2: If I remove the code in startup.cs, and add the code in web.config, I start getting the header, but also start getting a 404 response looking for signalr/hubs. Having the code in startup.cs and the webconfig gives me this error: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed.