与CORS和IE9 ASP网页API POST请求(XDomainRequest对象) [英] ASP Web API POST request with CORS and IE9 (XDomainRequest object)

查看:310
本文介绍了与CORS和IE9 ASP网页API POST请求(XDomainRequest对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经快疯了这里试图让jquery.ajax与IE9工作。所以我有一个实现CORS一个ASP的Web API 2 REST API。从所有的浏览器请求CORS工作。 IE9没有工作,因为它使用的XDomainRequest。我设法得到它也通过ajaxTransport的自定义实现了IE9工作。

I've been going crazy here trying to get jquery.ajax to work with ie9. So I have a ASP Web API 2 Rest API that implements CORS. CORS requests from all browsers work. IE9 didnt work since it uses the XDomainRequest. I managed to get it too work by making a custom implementation of ajaxTransport for IE9.

现在GET请求似乎很好地工作。但是,当我从IE9做一个post请求我得到一个HTTP错误415 - unsuportted媒体类型

Right now GET requests seem to work fine. But when I do a post request from IE9 I get a HTTP error 415 - unsuportted media type.

我已经设置了内容类型为:应用/ JSON,我也试过应用程序/ x-WWW的形式urlen codeD,但是从我的理解XDomainRequest犯规支持一切自定义页眉?有谁知道,如果事情的具体需求是对的WebAPI设置或者我需要调整的要求?

I've set the content-type to:"application/json" and I've also tried "application/x-www-form-urlencoded", but from what I understood XDomainRequest doesnt support everything with custom headers? Does anybody know if something specific needs to be setup on the WebAPI or do I need to tweak the request?

我的要求是这样的:

                        $.ajax({
                        url: hostname + "/api/DDC/Book",
                        type: "POST",

                        contentType: "application/json",
                        data: {
                            DealID: function () {
                                return viewModel.get("DealID");
                            },
                            LocationID: function () {
                                return viewModel.get("LocationID");
                            },
                            Time: function () {
                                return viewModel.get("selectedDateTime.Time");
                            }

                        }
                    })

在服务器我有这样的:

[HttpPost("DDC/Book")]
    [EnableCors(origins: "*", headers: "*", methods: "POST, GET, OPTIONS, PUT, DELETE")]
    public dynamic Post(BookModel model)
    {
       .........

当我分析了IE浏览器调试失败请求这是被发送出去的请求头:

When I analyze the failed request in the IE debugger this are the request headers that get sent out:

Key Value
Request POST //api/DDC/Book HTTP/1.1
Accept  */*
Origin  http://myurl.com
Accept-Language hr-HR
Accept-Encoding gzip, deflate
User-Agent  Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Host    www.somehost.com
Content-Length  55
DNT 1
Connection  Keep-Alive
Cache-Control   no-cache

我真的失去了所有希望在这里和IE是让我发疯。(该死你微软:D),所以任何帮助或建议是大大appriciated

I'm really losing all hope here and IE is making my go crazy (damn you Microsoft :D ), so any help or advice is much appriciated.

编辑:从更reasearch我发现的WebAPI需要一个内容类型的工作和XDomainRequest犯规送出之一。因此,我认为唯一的解决办法是调整过我的WebAPI没事的时候设置为有一个默认的内容类型。不知道如何将这种尚未虽然

From more reasearch I found out that WebAPI requires a content-type to work and XDomainRequest doesnt send out one. So the only solution I see is too tweak my webapi to have a default content-type when nothing is set. Don't know how to this yet though

EDIT2:攻击我的方式,通过暂时改变我所有的岗位,得到,不知道如何聪明的是这一点,但我现在看不出有什么大问题,所以它会做,直到我解决这个问题。

Hacked my way through temporarily by transforming all my POSTs, to GETs, dont know how smart is this, but I see no bigger problem with it now, so it will do until I fix the problem

推荐答案

设法解决它自己。当有正如指出的雷Nicholus没有Content-Type的ASP网页API默认为应用程序/八位字节流内容类型。我需要应用程序/ x-WWW的形式urlen codeD的默认值。

Managed to solve it myself. As pointed by Ray Nicholus when there is no Content-Type ASP Web API defaults to an "application/octet-stream" Content-Type. I need a default of "application/x-www-form-urlencoded".

我设法通过编写了一个检查传入请求的Content-Type和我自己的简单消息处理程序才达到这一点,如果没有什么是present它增加了一个应用程序/ x-WWW的形式urlen codeD 一。

I managed to achive this by writing my own simple message handler that checks an incoming requests "Content-Type" and if nothing is present it adds an "application/x-www-form-urlencoded" one.

这是code:

public class DefaultContentTypeMessageHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Content.Headers.ContentType == null)
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");


        var response = await base.SendAsync(request, cancellationToken);


        return response;
    }

}

更新:

由于在评论写的罗伯特·基督下面我延长了答案有点为那些谁以前没​​有使用消息处理程序的工作:

As written by Robert Christ in the comment below I am extending the answer a bit for those who have not worked with message handlers before:

对于那些谁不乍一看明白,DelegatingHandlers
  允许你修改的请求/响应对象,他们真的打前
  该框架的WebAPI内部。闲来无事在该框架确实
  让你修改模型前传入的请求绑定,无
  实际编写自定义模型粘合剂(eugh)。所以不是,在这里,你
  能嗅出一个空的内容类型(这是由缺陷担保
  在XDomainRequest规范),其更新到XML或JSON,你会
  能够正确地分析传入的请求。

For those who don't understand at first glance, DelegatingHandlers allow you to modify requests / response objects before they really hit the WebAPI framework internals. Nothing else in the framework really lets you modify the incoming request before model binding, without actually writing custom model binders (eugh). so instead, here, you can sniff out a null content type (which is guaranteed by shortcomings in the XDomainRequest spec), update it to xml or json, and you will be able to parse the incoming request correctly.

你写你需要的WebAPI进行注册的消息处理程序之后。你这样做,在WebApiConfig类:

After you have written a message handler you need to register it with WebAPI. You do that in the WebApiConfig class:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        config.MessageHandlers.Add(new DefaultContentTypeMessageHandler());
        // Rest of your code

     }
 }

这篇关于与CORS和IE9 ASP网页API POST请求(XDomainRequest对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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