【发布时间】:2020-01-11 18:55:11
【问题描述】:
我有一个网站,其中包含一些使用 ASP.NET MVC Ajax 的表单。 BeginForm方法的一个例子:
@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 参数,该 URL 被设置为与浏览器从中获取该 URL 的域不同的域。这样做是因为主站点是使用 CDN 静态托管的,而表单是使用 AJAX 从另一个域加载的。这有效,除了 cookie 不在 AJAX 请求中发送。我试图通过使用OnBegin 事件和这个JavaScript 设置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 设置为主(静态)站点域。
更新:通过更多控制台日志记录,我已经验证传递给我的 OnBegin 事件处理程序 (SetWithCredentialsTrue) 的 xhr 参数不是 XMLHttpRequest 对象,因此设置 @987654322 @ 对它没有影响。 所以问题是如何访问 XMLHttpRequest 对象?
【问题讨论】:
标签: asp.net-mvc cross-domain asp.net-ajax