So I want to enable CORS on my .net web API but the client application keeps getting 404 for the options request and a second error:
Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: it does not have http ok status
I have followed step by step what Microsoft website outline and I am still unsuccessful.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Added this line to my WebApiConfig.cs file
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
I also tried it by adding the headers in the Web.config in the httpProtocol tag file like so:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
</customHeaders>
</httpProtocol>
Try to enable from the web.config file under <system.webserver></system.webserver> like so:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Credentials" value="true"/>
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, OPTIONS" />
</customHeaders>
</httpProtocol>
To handle the preflight request error add the line below in the <handlers></handlers> tags:
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" requireAccess="None" responseBufferLimit="4194304" />
Then in the Global.asax file, add the following method:
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.Flush();
}
}
Try this:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
And in your api controller
:
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class TestController : ApiController
{
}
If you wanted to enable it per action method, do this:
[EnableCors(origins: "*", headers: "*", methods: "*")]
public HttpResponseMessage Get() { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With