2017-04-05 57 views
1

我有了某种形式使用ASP.NET MVC Ajax的网站。 BeginForm方法的一个例子:ASP.NET MVC Ajax表单提交跨域不发送饼干

@using (Ajax.BeginForm("HandleSignin", "Profile", null, new AjaxOptions() { 
     HttpMethod = "POST", 
     Url = Url.Action("HandleSignin", "Profile", null, Request.Url.Scheme), 
     OnBegin = "SetWithCredentialsTrue(xhr)", 
     InsertionMode = InsertionMode.Replace, 
     UpdateTargetId = "signin-form-container" }, 
    new { id = "sign-in-form", @class = "text-left-desktop group" })) 
{ 
    @Html.AntiForgeryToken() 
    @Html.TextBoxFor(x => Model.Email, new { placeholder = "Email" }) 
    @Html.PasswordFor(x => Model.Password, new { placeholder = "Password" }) 
    <input type="submit" value="SignIn" class="button small-button"> 
} 

注意,因为在该Url.Action方法的Request.Url.Scheme PARAM中,URL被设置为比浏览器从得到这个域不同的域。这是因为主站点使用CDN静态托管,而表单使用AJAX从另一个域加载。这是有效的,只是cookie不会在AJAX请求中发送。我想有和这个JavaScript通过使用OnBegin事件设置xhr.withCredentials = true发送的cookie:

<script type="text/javascript"> 
    function SetWithCredentialsTrue(xhr) { 
     console.log("SetWithCredentialsTrue(xhr)", xhr); 
     xhr.withCredentials = true; 
    } 
</script> 

虽然我可以看到SetWithCredentialsTrue()方法被调用,它似乎并没有工作在产生的HTTP请求时,表单提交时没有Cookie标头。

所有服务器端处理程序都将Access-Control-Allow-Credentials响应标头设置为true,将Access-Control-Allow-Origin设置为主(静态)站点域。

UPDATE:一些更多的控制台日志,我已经验证xhr参数传递给我的OnBegin事件处理程序(SetWithCredentialsTrue)不是一个XMLHttpRequest对象,因此设置就可以了withCredentials没有产生影响。 所以问题是我如何访问XMLHttpRequest对象?

回答

1

我终于想通了这一点。 XMLHttpRequest对象不通过ASP.NET MVC库公开。我能够改变jquery.unobtrusive-ajax.js,由ASP.NET MVC助手使用的JS库使它集withCredentials为true:

$(document).on("submit", "form[data-ajax=true]", function (evt) { 
    var clickInfo = $(this).data(data_click) || [], 
     clickTarget = $(this).data(data_target), 
     isCancel = clickTarget && clickTarget.hasClass("cancel"); 
    evt.preventDefault(); 
    if (!isCancel && !validate(this)) { 
     return; 
    } 
    asyncRequest(this, { 
     url: this.action, 
     type: this.method || "GET", 
     data: clickInfo.concat($(this).serializeArray()), 
     xhrFields: { 
      withCredentials: true 
     } 
    }); 
}); 

注:xhrFields是我加的部分。

0

按我的理解,你试图做的是,你想从一个域将数据发送给使用AJAX后右另一个域是什么?

如果这是真的话,我想告诉你的浏览器不允许你这样做,因为安全问题。

如果你仍然想这样做,那么你有两个选项的使用CORS和JSONP。

http://csharp-video-tutorials.blogspot.in/2016/09/calling-aspnet-web-api-service-in-cross.html

http://csharp-video-tutorials.blogspot.in/2016/09/cross-origin-resource-sharing-aspnet.html

+0

的问题是关于从一个域提交ASP.NET MVC AJAX形式到另一个。我可以通过设置'xhr.withCredentials = true'来使用JQuery进行类似的请求,但是我想从ASP.NET MVC Ajax表单中做同样的事情。否则,CORS正在工作 - 表单提交,它只是不发送cookie头。 – Alex