Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebAPI CORS - why is the OPTIONS request making its way into my Controller?

I have CORS working with the following:

[System.Web.Http.HttpPut]
[System.Web.Http.AcceptVerbs("OPTIONS")]
[System.Web.Http.Route("api/exercise")]
public HttpResponseMessage UpdateExercise(Exercise exercise) {
    try {
        _adminService.UpdateExercise(exercise);
        return Request.CreateResponse(HttpStatusCode.OK, "Success");
    } catch (Exception e) {
        return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
    }
}

In my global.asax:

protected void Application_BeginRequest() {
    if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS") {
        Response.Flush();
    }
}

But something weird is happening - if I set a breakpoint in my controller, the OPTIONS request makes its way to the innards with a null exercise. Why is this happening? I would expect the Flush() to prevent this.

As it stands, I need to add checks for null to all of my CORS-sensitive endpoints (PUTs, DELETEs). This seems inelegant... should I be able to prevent OPTIONS requests from hitting the controller logic, instead just responding with the required headers straight-away?

like image 813
SB2055 Avatar asked Jun 16 '14 23:06

SB2055


People also ask

How do I fix the CORS issue in Web API?

You can enable CORS per action, per controller, or globally for all Web API controllers in your application. To enable CORS for a single action, set the [EnableCors] attribute on the action method. The following example enables CORS for the GetItem method only.

Why is options request sent?

The OPTIONS request method is sent by browsers to find out the supported HTTP methods and other parameters supported for the target resource before sending the actual request. Browsers send OPTIONS requests when they send a CORS request to another origin.

Why is there an options request before post?

Prevent sending the post data, if it wont be processed This is the only reason what is valid. Using options request will prevent sending the post data to the server unnecessarily.


1 Answers

Adding this as an answer, based on the comments in the question.

The problem is caused by accepting the OPTIONS verb on the action method. The MVC runtime then tries to execute the action method & the null problem occurs.

Remove the verb so MVC doesn't try to execute the method & the Application_BeginRequest event will sort out the pre-flight issue for you.

like image 104
Carl Heinrich Hancke Avatar answered Nov 15 '22 11:11

Carl Heinrich Hancke