跨域Json在IE,Firefox和Chrome上取得了成功,但在Firefox和Chrome上都报告了一个空错误

时间:2012-11-03 20:44:07

标签: asp.net json asp.net-web-api

我正在使用asp.net web api进行跨域json帖子。在我的服务/服务器端,我有以下方法来响应POST请求:

// POST api/<controller>
public HttpResponseMessage Post(Customer newCustomer)
{
    DataClassesDataContext db = new DataClassesDataContext();
    var response = Request.CreateResponse<Customer>(HttpStatusCode.Created, newCustomer);

    db.Customers.InsertOnSubmit(newCustomer);
    db.SubmitChanges();

    string uri = Url.Link("DefaultApi", new { id = newCustomer.Id });
    response.Headers.Location = new Uri(uri);

    return response;
}

在客户端,运行在不同的端口号(即跨域),我使用以下jQuery代码:

<body>

<input type="button" value="click me" onclick="hello()" />

<script type="text/javascript">
    function hello() {
        //SEE: http://stackoverflow.com/questions/5241088/jquery-call-to-webservice-returns-no-transport-error
        $.support.cors = true;

        //var jsonObjects = [{ Name: "Name1", CellphoneNum: 1234657911 }];

        $.ajax({
            url: "http://localhost:26037/api/customer",
            type: "POST",
            crossDomain: true,
            data: { Name: "Name321", CellphoneNum: 1234657922 },
            dataType: "json",

            success: function (result) {
                alert("Success");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('Thrown Error: ' + thrownError);
                alert('xhr status: ' + xhr.status);
            }
        });
    }
    </script>
</body>

我的问题是,从客户端,IE上将显示成功警报消息,并使用POST方法中的LINQ代码将数据插入数据库。但是,使用Chrome或Firefox时,数据也会插入到数据库中,LINQ代码将成功执行,但会显示一个空字符串错误和0 xhr状态的消息框。

为什么在数据在服务器中发布并成功处理后,它只报告Firefox和Chrome上的错误?

2 个答案:

答案 0 :(得分:1)

看起来浏览器在报告xhr错误方面做得不好。以下教程可以帮助您。此外,如果您尚未这样做,请确保将服务器端的“Access-Control-Allow-Origin”标头设置为您要允许的客户端域,或者将“*”设置为允许所有跨域请求。 / p>

一般CORS教程:http://www.html5rocks.com/en/tutorials/cors/

ASP.net和CORS: http://encosia.com/using-cors-to-access-asp-net-services-across-domains/

答案 1 :(得分:1)

要进行跨域调用,我在IIS上部署了web应用程序根文件夹中的crossdomain.xml。 with cross domain.xml具有以下内容。

<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="*"/>
</cross-domain-policy>

我希望它也会适用你的情况。