Ajax CORS调用不适用于application / json

时间:2017-08-25 23:46:48

标签: ajax asp.net-web-api cors content-type

我的以下代码工作正常,我可以致电API

$.ajax({
    url: "http://localhost:57786/mvc/create",
    method: "POST",            
    data: { FirstName: "ABC", LastName: "XYZ" },
    success: function (data) {
        alert("Success");
    },
    error: function (statusText, error) {
        alert("Error");
    }
});

但是以下代码无效,我无法拨打API

    $.ajax({
        url: "http://localhost:57786/mvc/create",
        method: "POST",
        data: JSON.stringify({ FirstName: "ABC", LastName: "XYZ" }),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            alert("Success");
        },
        error: function (statusText, error) {
            alert("Error");
        }
    });

以下是API代码

[EnableCors("*","*","*")]
public class MVCController : Controller
{
    // POST: MVC/Create
    [HttpPost]
    public ActionResult Create(MyData value)
    {
         //My Code
    }
}

我收到回复The response had HTTP status code 404.

当我使用contentTypeapplication/json时,为什么Ajax调用失败?

1 个答案:

答案 0 :(得分:1)

有类似的问题,我通过在web.config的system.webserver中添加一些配置来解决它,也可以将其写为自定义过滤器属性,然后将其注册到App_start文件夹中的filterconfig.cs中。

 <system.webserver>
       <httpProtocol>
        <customHeaders>
           <add name="Access-Control-Allow-Origin" value="*" />
           <add name="Access-Control-Allow-Headers" value="Content-Type" />
         <add name="Access-Control-Allow-Methods" value="GET, POST, PUT,DELETE,OPTIONS"/>
        </customHeaders>
     </httpProtocol>
 </system.webserver>

<-这是用于Web的配置->

或对于filterconfig.cs,您可以编写一个自定义过滤器并覆盖ActionFilterAttribute,但是请注意,这样做的挑战在于,诸如/ token之类的操作无法生成授权令牌,因为它不满足onActionExecuting方法,因此可能会失败,所以也许您可能想使用web.config

   public class CustomHeaderAttributeFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //add in your custom headers
        filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type");
        filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods", "GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS");

        base.OnActionExecuting(filterContext);
    }

    public void OnException(ExceptionContext filterContext)
    {
        //do some cool exception handling here
    }
}

}