如何支持HTTP选项动词在ASP.NET MVC /的​​WebAPI应用 [英] How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

查看:519
本文介绍了如何支持HTTP选项动词在ASP.NET MVC /的​​WebAPI应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经安装ASP.NET Web应用程序开始用MVC 4 /网络API模板。它好像事情是工作真的很好 - 没有任何问题,我所知道的。我用Chrome和Firefox要经过的站点。我已经使用招测试,所有的反应似乎是在钱上。

I've setup an ASP.NET web application starting with a MVC 4/Web API template. It seems as though things are working really well - no problems that I'm aware of. I've used Chrome and Firefox to go through the site. I've tested using Fiddler and all of the responses seem to be on the money.

所以,现在我开始写一个简单的Test.aspx的消费这个新的Web API。脚本的相关部分:

So now I proceed to write a simple Test.aspx to consume this new Web API. The relevant parts of the script:

<script type="text/javascript">
    $(function () {

        $.ajax({
            url: "http://mywebapidomain.com/api/user",
            type: "GET",
            contentType: "json",
            success: function (data) {

                $.each(data, function (index, item) {

                    ....

                    });
                }
                );

            },
            failure: function (result) {
                alert(result.d);
            },

            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("An error occurred, please try again. " + textStatus);
            }

        });

    });
</script>

这会产生一个请求头:

OPTIONS http://host.mywebapidomain.com/api/user HTTP/1.1
Host: host.mywebapidomain.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://mywebapidomain.com
Access-Control-Request-Method: GET
Access-Control-Request-Headers: content-type
Connection: keep-alive

由于是,网络API返回405不允许的方法。

As is, Web API returns a 405 Method Not Allowed.

HTTP/1.1 405 Method Not Allowed
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/xml; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 30 Sep 2013 13:28:12 GMT
Content-Length: 96

<Error><Message>The requested resource does not support http method 'OPTIONS'.</Message></Error>

据我所知,OPTIONS动词未连接在默认的Web API控制器。所以,我把下面的code在我UserController.cs:

I understand that the OPTIONS verb is not wired up in Web API controllers by default... So, I placed the following code in my UserController.cs:

// OPTIONS http-verb handler
public HttpResponseMessage OptionsUser()
{
    var response = new HttpResponseMessage();
    response.StatusCode = HttpStatusCode.OK;
    return response;
}

...这消除了405不允许的方法错误,但反应完全是空的 - 没有数据返回:

...and this eliminated the 405 Method Not Allowed error, but the response is completely empty - no data is returned:

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 30 Sep 2013 12:56:21 GMT
Content-Length: 0

必须有额外的逻辑......我不知道如何正确code选项的方法或控制器甚至是适当的地方放置code。奇怪的Web API网站正常启用从Firefox或Chrome,但上面的错误了。阿贾克斯调用查看时(对我来说)。我该如何处理preflight检入阿贾克斯code?也许我应该解决这个问题在客户端的阿贾克斯逻辑?或者,如果这是在服务器端的问题,由于没有处理OPTIONS动词。

There must be additional logic... I don't know how to properly code the Options method or if the controller is even the proper place to put the code. Weird (to me) that the Web API site responds properly when viewed from Firefox or Chrome, yet the .ajax call above errors out. How do I handle the "preflight" check in the .ajax code? Maybe I should be addressing this issue on the client side's .ajax logic? Or, if this is an issue on the server side due to not handling the OPTIONS verb.

谁能帮助?这必须是一个非常普遍的问题,我很抱歉,如果它已经在这里找到答案。我搜查,但没有发现任何方式帮助任何答案。

Can anyone help? This must be a very common issue and I apologize if it's been answered here. I searched but didn't find any answers that helped.

更新 恕我直言,这是一个客户端的问题,是同阿贾克斯JQuery的code以上。我这样说是因为提琴手不显示任何错误405头时,我从一个Web浏览器访问mywebapidomain / API /用户。我可以复制这个问题的唯一地方是从jQuery阿贾克斯()调用。此外,相同的Ajax调用上面正常工作的服务器(同一个域)在运行时。

UPDATE IMHO, this is a client side issue and has to do with the Ajax JQuery code above. I say this because Fiddler doesn't show any 405 error headers when I access mywebapidomain/api/user from a web browser. The only place I can duplicate this problem is from the JQuery .ajax() call. Also, the identical Ajax call above works fine when ran on the server (same domain).

我发现了另一篇文章:<一个href="http://stackoverflow.com/questions/13814739/prototype-ajax-request-being-sent-as-options-rather-than-get-results-in-501-err">Prototype Ajax请求被发送的选项,而不是GET;导致501错误,这似乎是相关的,但我已经修补了他们没有成功的建议。显然,jQuery是codeD,这样,如果一个Ajax请求的跨域(这是我的),它增加了一些头 - 触发选项头莫名其妙的。

I found another post: Prototype AJAX request being sent as OPTIONS rather than GET; results in 501 error that seems to be related, but I've tinkered with their suggestions with no success. Apparently, JQuery is coded so that if an Ajax request is cross domain (which mine is) it adds a couple of headers which trigger the OPTIONS header somehow.

'X-Requested-With': 'XMLHttpRequest',
'X-Prototype-Version': Prototype.Version,

这似乎只是应该不是修改核心code在JQuery的...可更好的解决方案。

It just seems that there should be a better solution available than modifying core code in JQuery...

下面提供的答案假设这是一个服务器端的问题。也许,我想,但我倾向于客户端和通话功能的托管服务提供商是不会帮助。

The answer provided below assumes this is a server side issue. Maybe, I guess, but I lean toward client and calling a hosting provider isn't going to help.

推荐答案

由于丹尼尔A.怀特在他的评论说,OPTIONS请求很有可能是客户端的跨域JavaScript的请求的一部分创建的。这是由跨地资源共享(CORS)兼容的浏览器自动完成。该请求是一个preliminary或的 $ P $对 - 飞行的请求,则实际AJAX请求,以确定哪个请求的动词及标头支持CORS之前完成。该服务器可以选择支持它没有,所有的HTTP动词还是有的。

As Daniel A. White said in his comment, the OPTIONS request is most likely created by the client as part of a cross domain JavaScript request. This is done automatically by Cross Origin Resource Sharing (CORS) compliant browsers. The request is a preliminary or pre-flight request, made before the actual AJAX request to determine which request verbs and headers are supported for CORS. The server can elect to support it for none, all or some of the HTTP verbs.

要完成的图片,AJAX请求有一个额外的原产地标题,并确定了托管的JavaScript原始页面是由担任的位置。服务器可以选择从任何来源支持的要求,或只为一组已知的,值得信赖的来源。允许任何来源是一个安全风险,因为就是可以增加跨站请求伪造(CSRF)的风险。

To complete the picture, the AJAX request has an additional "Origin" header, which identified where the original page which is hosting the JavaScript was served from. The server can elect to support request from any origin, or just for a set of known, trusted origins. Allowing any origin is a security risk since is can increase the risk of Cross site Request Forgery (CSRF).

所以,你需要启用CORS。

So, you need to enable CORS.

下面是解释如何做到这一点在ASP.Net的Web API的链接

Here is a link that explains how to do this in ASP.Net Web API

<一个href="http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors">http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors

的实施说明有允许您指定,除其他事项外

The implementation described there allows you to specify, amongst other things

  • 在CORS支持在每个动作,每个控制器或全球范围
  • 支持的来历
  • 当启用CORS AA控制器或全球层面上,支持HTTP动词
  • 服务器是否支持发送与跨域请求凭证

在一般情况下,这工作得很好,但是你需要确保你是知道的安全隐患,特别是如果你允许来自任何域交叉起源的请求。非常仔细,然后让这一点。

In general, this works fine, but you need to make sure you are aware of the security risks, especially if you allow cross origin requests from any domain. Think very carefully before you allow this.

在这方面的浏览器都支持CORS,维基百科说下面的引擎支持:

In terms of which browsers support CORS, Wikipedia says the following engines support it:

  • 在Gecko的1.9.1(火狐3.5)
  • 的WebKit(Safari 4中,铬3)
  • 在MSHTML /三叉戟6(IE10)与IE8部分支持和9
  • preSTO(歌剧12)

<一个href="http://en.wikipedia.org/wiki/Cross-origin_resource_sharing#Browser_support">http://en.wikipedia.org/wiki/Cross-origin_resource_sharing#Browser_support

这篇关于如何支持HTTP选项动词在ASP.NET MVC /的​​WebAPI应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆