I recently read this code that makes an MVC Web API allow CORS (Cross origing resource sharing). I understand that the ActionFilterAtrribute
makes this a filter, but I'm not sure what's going on in this class: AllowCORS
.
public class AllowCORS : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(filterContext.HttpContext.Request.HttpMethod == "OPTIONS")
{
filterContext.Result = new EmptyResult();
}
else
{
base.OnActionExecuting(filterContext);
}
}
}
So basically, if the request method we receive is a HttpOPTIONS
we do something which I don't quite understand in this case. Otherwise, we do something else that I'm not sure about either?
What's actually going on here?
In ActionFilterAttribute
class, OnActionExecuting
executes just before the execution of the controller action on which ActionFilterAttribute
attribute is placed.
If you override OnActionExecuting
function, it allows you to execute any certain code before the execution of controller action. In your case:
if(filterContext.HttpContext.Request.HttpMethod == "OPTIONS")
{
filterContext.Result = new EmptyResult();
}
If the request is HttpOPTIONS
then before execution of controller action, the code returns an empty response to the client.
And if the request is of some other type:
else
{
base.OnActionExecuting(filterContext);
}
It will allow the controller action to execute and return response to the client.