我有 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/