【问题标题】:WebAPI CORS - why is the OPTIONS request making its way into my Controller?WebAPI CORS - 为什么 OPTIONS 请求进入我的控制器?
【发布时间】:2014-08-06 20:59:58
【问题描述】:

我有 CORS 使用以下内容:

[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);
    }
}

在我的global.asax

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

但是发生了一些奇怪的事情 - 如果我在控制器中设置断点,则 OPTIONS 请求会通过 null 练习进入内部。为什么会这样?我希望Flush() 可以防止这种情况发生。

就目前而言,我需要为所有对 CORS 敏感的端点(PUT、DELETE)添加对 null 的检查。这似乎不优雅...我是否应该能够阻止 OPTIONS 请求访问控制器逻辑,而不是直接使用所需的标头进行响应?

【问题讨论】:

  • @CarlHancke - 成功了。看起来我已经实现了另一种方法的一半......随时发布作为答案,非常感谢:)

标签: asp.net-web-api cors asp.net-web-api2 http-options-method


【解决方案1】:

根据问题中的 cmets 将其添加为答案。

问题是由在操作方法上接受OPTIONS 动词引起的。然后 MVC 运行时尝试执行操作方法并出现null 问题。

删除动词,以便 MVC 不会尝试执行该方法,Application_BeginRequest 事件将为您解决飞行前问题。

【讨论】:

    猜你喜欢
    • 2015-11-24
    • 2016-12-09
    • 2017-05-26
    • 1970-01-01
    • 2015-09-01
    • 2015-06-11
    • 2015-03-01
    • 2018-11-19
    • 1970-01-01
    相关资源
    最近更新 更多