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

天大地大妈咪最大 提交于 2019-12-05 23:26:36

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/24253802/webapi-cors-why-is-the-options-request-making-its-way-into-my-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!