CORS的WebAPI - 为什么OPTIONS请求正在进入我的控制器? [英] WebAPI CORS - why is the OPTIONS request making its way into my Controller?
问题描述
我CORS具有以下工作:
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);
}
}
在我的的Global.asax
:
protected void Application_BeginRequest() {
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS") {
Response.Flush();
}
}
不过,奇怪的事情发生了 - 如果我在我的控制器设置一个断点,OPTIONS请求使得其方式与空
锻炼内脏。这究竟是为什么?我期望同花顺()
来prevent这一点。
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.
既然这样,我需要为空加检查,我所有的CORS敏感的端点(放,删除)。这似乎不雅......我应该能够prevent OPTIONS请求击中控制器逻辑,而不是只与所需的头直走应对的呢?
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?
推荐答案
添加此作为一个答案,根据问题的意见。
Adding this as an answer, based on the comments in the question.
问题是由接受的操作方法的选项
动词引起的。 MVC的运行然后试图执行的操作方法和放大器;出现空
的问题。
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.
删除动词所以MVC不会尝试执行方法和放大器;在的Application_BeginRequest
活动将挑选出pre-飞行的问题给你。
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.
这篇关于CORS的WebAPI - 为什么OPTIONS请求正在进入我的控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!