Ajax json 跨域发布到控制器,“不允许"访问控制允许标题 [英] Ajax json post to Controller across domains, "not allowed by" Access-Control-Allow-Headers

查看:30
本文介绍了Ajax json 跨域发布到控制器,“不允许"访问控制允许标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的 MVC 控制器操作,它需要一些 json 数据 - 然后返回 true 或 false.

I create a simple MVC Controller action, that takes some json data - then return true or false.

    [AllowCrossSiteJson]
    public JsonResult AddPerson(Person person)
    {
            //do stuff with person object
           return Json(true);
    }

我从 javascript 调用它:

I call it from javascript:

        function saveData(person) {
            var json = $.toJSON(person); //converts person object to json
            $.ajax({
                url: "http://somedomain.com/Ajax/AddPerson",
                type: 'POST',
                dataType: 'json',
                data: json,
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    alert("ok");
                }
            });
        }

只要我在同一个域中一切正常,但是一旦我从另一个域调用它,我就会遇到问题.

Everything works as long as I am on the same domain, but as soon as I call it from another domain, I run into problems.

在控制器上有一个动作过滤器AllowCrossSiteJson",它把标题Access-Control-Allow-Origin"设置为*",允许任何来源访问控制器动作.

On the controller is an action filter "AllowCrossSiteJson" that sets the header "Access-Control-Allow-Origin" to "*", allowing any origin to access the controller action.

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}

但是 - 然后我在跨域调用时在萤火虫中收到此错误:

However - I then get this error in firebug, when calling across domains:

选项 http://somedomain.com/Ajax/AddPerson?packageId=3500内部服务器错误)XMLHttpRequest 无法加载 http://somedomain.com/Ajax/AddPerson.Access-Control-Allow-Headers 不允许请求标头字段 Content-Type.

OPTIONS http://somedomain.com/Ajax/AddPerson?packageId=3 500 (Internal Server Error) XMLHttpRequest cannot load http://somedomain.com/Ajax/AddPerson. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.

这里有什么问题?

我已经研究了几个小时的可能解决方案,这似乎与使用 OPTIONS 的 jquery 有关(不是我期望的 POST).

I have been looking through possible solutions for hours, and it seems to be something to do with jquery using OPTIONS (not POST as I would expect).

如果确实是这个问题,我该如何解决?

If that is indeed the problem, how can I fix that?

推荐答案

我推荐你 JSONP,它是只有真正的跨浏览器和可靠的跨域 AJAX 解决方案.因此,您可以首先编写一个自定义操作结果,该结果将使用回调包装 JSON 响应:

I'd recommend you JSONP, it's the only really cross browser and reliable solution for cross domain AJAX. So you could start by writing a custom action result that will wrap the JSON response with a callback:

public class JsonpResult : ActionResult
{
    private readonly object _obj;

    public JsonpResult(object obj)
    {
        _obj = obj;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var serializer = new JavaScriptSerializer();
        var callbackname = context.HttpContext.Request["callback"];
        var jsonp = string.Format("{0}({1})", callbackname, serializer.Serialize(_obj));
        var response = context.HttpContext.Response;
        response.ContentType = "application/json";
        response.Write(jsonp);
    }
}

然后:

public ActionResult AddPerson(Person person)
{
    return new JsonpResult(true);
}

最后执行跨域AJAX调用:

and finally perform the cross domain AJAX call:

$.ajax({
    url: 'http://somedomain.com/Ajax/AddPerson',
    jsonp: 'callback',
    dataType: 'jsonp',
    data: { firstName: 'john', lastName: 'smith' },
    success: function (result) {
        alert(result);
    }
});

这篇关于Ajax json 跨域发布到控制器,“不允许"访问控制允许标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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