asp.net-web-api - WebAPI CORS - 为什么 OPTIONS 请求进入我的 Controller ?

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

我有 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();
    }
}

但是发生了一些奇怪的事情——如果我在我的 Controller 中设置了一个断点,OPTIONS 请求就会以 null 进入内部。锻炼。为什么会这样?我希望 Flush()以防止这种情况。

就目前而言,我需要向所有对 CORS 敏感的端点(PUT、DELETE)添加 null 检查。这似乎不雅......我应该能够阻止 OPTIONS 请求击中 Controller 逻辑,而不是直接响应所需的 header 吗?

最佳答案

根据问题中的评论,将此添加为答案。

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

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

关于asp.net-web-api - WebAPI CORS - 为什么 OPTIONS 请求进入我的 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24253802/

相关文章:

html - 如何根据 Web API/Asp.Net Identity 验证 HTML-5 音频下载请求?

c# - 如何从 IOwinContext 获取 HttpRequestBase

c# - 用于 API 版本控制的 Web API 2 属性路由

c# - 如何设计用于批量插入和更新的 Restful API?

c# - 如何从 WebAPI 中删除转义字符

github - GitHub Pages上的跨源资源共享

javascript - CORS 支持不适用于域

javascript - Node 的 CORS 问题

c# - 发布 Web API 2 应用程序后出现 HTTP 405 错误

rest - Azure API 管理响应 404