AJAX跨域调用ASP.NET MVC的问题及解决方案

AJAX跨域调用ASP.NET MVC的问题及解决方案

问题描述:

解决方法:

只需要在web.config中添加如下标为红色的内容即可:

<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>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>

针对ASP.NET Web API,除了上面这样的设置,还需要添加一个特殊的设计,就是为每个APIController添加一个OPTIONS的方法,但无需返回任何东西。

public string Options()
{
return null; // HTTP 200 response with empty body
}

注意:

当需要cookie做身份验证时会出错:

表头中可看到set-cookie但是,浏览器添加不上。

解决方法:

1."Access-Control-Allow-Origin"对应的值不能为通配符“*”。徐添加request headers中的origin的值。

2.在web.config中添加一下代码表示允许跨域发送Cookie

 <add name="Access-Control-Allow-Credentials" value="true" />

3.在ajax请求中应加入xhrFields: {withCredentials: true},否则,依然不会发送Cookie

  function clickAjax() {
        $.ajax({
            type: "post",
            data:{UserName:"admin",PassWord:"123",BtnSubmit:"Login"},
            xhrFields: {withCredentials: true},
            url: "http://localhost:13250/Authentication/DoJsonResult",
            success: function (result) {
                console.log(result);
                window.location.href = "clickajax.html"
            }
        });
    }

参考资料:

https://www.cnblogs.com/chenxizhang/p/3821703.html

https://blog.csdn.net/a317560315/article/details/78397369

原文地址:https://www.cnblogs.com/s313139232/p/9117175.html