Ajax json post to Controller across domains, “not allowed by” Access-Control-Allow-Headers

前端 未结 2 1413
梦毁少年i
梦毁少年i 2020-12-03 06:18

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

    [AllowCrossSiteJson]
    public JsonResult AddPerson(Per         


        
相关标签:
2条回答
  • 2020-12-03 06:40

    To fix the Access-Control-Allow-Origin error, you need to include the following header in your response:

    Access-Control-Allow-Headers: Content-Type

    Basically, any "non-simple" header needs to be included as a comma-delimited list in the header above. Check out the CORS spec for more details:

    http://www.w3.org/TR/cors/

    "Content-Type" needs to be included because "application/json" does not match the values defined here:

    http://www.w3.org/TR/cors/#terminology

    0 讨论(0)
  • 2020-12-03 06:58

    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);
        }
    }
    

    and then:

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

    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);
        }
    });
    
    0 讨论(0)
提交回复
热议问题