Angular 6 Asp.Net (not Core) Web Api CORS request fails
After struggling my head the whole morning and trying everything each one of you suggested here I cannot believe in the end my problem could have been resolved so easily.
Regarding @Madpop suggestion Application_BeginRequest (for any reason) was never being fired (dind't want to spend much time investigating why).
@Steveland solution involved adding dependency injection and it resulted a little bit complicated to me (I don't have much experience with that) aparte from the fact I'm not using Asp.Net Core but Asp.Net framework 4.6.
I was looking for a simple solution to a problem I thought it should have been easy to solve and the key was appending
[HttpPost]
[HttpOptions] //this was the key
[Authorize]
to Post method header. This was the only way for me to allow "Options" verb in request.
I don't know if this is the best way to accomplish this but for now it works (let me know what d'you think guys).
I appreciate ev'ry help I've received here from everybody and say thanks and as I'm not an expert on this subject (Angular + Web Api) I would like to finally ask the next:
Will I have to put this [HttpOptions] also for production when the api will be deployed to server or this is just needed for now for debugging and testing locally purposes?
Edit 1:
After testing I've noticed it works with self hosting Web Api but as I publish Web Api to my local IIS I get "415 Unsupported Media Type" in browser :(
Regarding the cors issue i also faced the similar issue i have created a global.asax file that i have place the below code
protected void Application_BeginRequest()
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://staging.example.com:8044");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Accepts, Content-Type, Origin, X-My-Header");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "60");
HttpContext.Current.Response.End();
}
}
it worked for me in angular 6 as well in ionic 3 also and before all these try to install https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
the above chrome plugin and activate it and then try to run the application