Reputation: 1227
I have an ASP.NET web form application with a couple of API controllers. One of my controllers gets a request from a different domain. Since this request contains an Authorization header the browser sends a preflight request (HTTP OPTIONS). At first, I tried to add the following in the web config :
<httpProtocol>
<customHeaders>
<add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, PATCH, DELETE"/>
<add name="Access-Control-Allow-Headers" value="accept, authorization, Content-Type"/>
<remove name="X-Powered-By"/>
</customHeaders>
</httpProtocol>
But it didn't work, and the browser failed with "405 - method not allowed" error. Only when adding the following code to global.asax I successfully received the preflight request
protected void Application_BeginRequest(object sender, EventArgs e)
{
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-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
HttpContext.Current.Response.End();
}
}
The thing that bothers me is that this code enables preflight request for all web API controllers, and I want to enable it only for one of my controllers. I know I can solve it using a function with [HttpOptions] annotation, but I don't want to add it for each function in the controller. Is there a way to enable it for all controller functions?
Upvotes: 0
Views: 2371
Reputation: 1549
Add this method to the Global.asax.cs and put this code
using System.Web;
namespace Example
{
public class Global : System.Web.HttpApplication
{
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");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
}
}
Upvotes: 2