mvc 3、jquery ajax &表单验证
在我的 MVC3 项目中,我有一个带有 [Authorize] 属性的控制器。 我有一个没有 ajax 的表单提交,如果用户没有登录,它会将用户(按预期)重定向到登录屏幕。
但是,现在我有一个使用 jquery ajax 提交的表单,我该如何做同样的事情吗?如果用户未获得授权,则将用户重定向到登录屏幕?成功登录后,用户应该被重定向到初始操作。
控制器
[Authorize]
[ValidateInput(false)]
public JsonResult SubmitChatMessage(string message)
{
if (!string.IsNullOrEmpty(message))
{
// Do stuff
}
// Return all chat messages
return GetChatMessages();
}
客户端JQUERY
$(document).ready(function () {
$("form[action$='SubmitChatMessage']").submit(function (event) {
$.ajax({
url: $(this).attr("action"),
type: "post",
dataType: "json",
data: $(this).serialize(),
success: function (response) {
// do stuff
}
});
return false;
});
});
我可以从firebug控制台窗口看到,服务器返回:
GET http://domain/Account/LogOn?ReturnUrl=%2fProductDetails%2fSubmitChatMessage
期待您的帮助!
更新了可能的解决方案
In my MVC3 project, I have a controller with an [Authorize] attribute.
I have a form submission without ajax, which redirects the user (as expected) to the login screen, if he/she is not logged in.
However, now I have a form which is submitted with jquery ajax, and how can I do the same thing? Redirect the user to the login screen, if he/she is not authorized? After a successful login, the user should is redirected to the initial action.
Controller
[Authorize]
[ValidateInput(false)]
public JsonResult SubmitChatMessage(string message)
{
if (!string.IsNullOrEmpty(message))
{
// Do stuff
}
// Return all chat messages
return GetChatMessages();
}
Client JQUERY
$(document).ready(function () {
$("form[action$='SubmitChatMessage']").submit(function (event) {
$.ajax({
url: $(this).attr("action"),
type: "post",
dataType: "json",
data: $(this).serialize(),
success: function (response) {
// do stuff
}
});
return false;
});
});
I can see from firebug console window, that the server returns:
GET http://domain/Account/LogOn?ReturnUrl=%2fProductDetails%2fSubmitChatMessage
Looking forward to your help!
UPDATED with possible solutions
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这是我一直讨厌关于 ASP.NET 中的表单身份验证的事情之一 - 根本不支持 AJAX 身份验证。再加上 IIS 处理 401 的问题,这可能会很痛苦。
有几种方法可以做到这一点,但没有一种方法特别“干净”。
其中包括:
在控制器中设置一个 ViewBag 标志,该标志对应于
Request.IsAuthenticated
,然后如果未通过身份验证,则将提交按钮单击事件重写到登录页面。使您的 AJAX 操作返回
JsonResult
,它是“code”的属性。其中代码 0 表示成功,1 表示未验证,2 表示其他数据问题等。然后在complete
$.ajax
回调中检查该代码并重定向到登录页面。检查
$.ajax
jqXHR
响应对象的状态代码403
,然后重定向到登录页面。为您的提交按钮编写一个自定义 HTML 帮助程序,它会呈现常规提交按钮或转到登录页面的锚标记,具体取决于身份验证状态。
编写一个自定义授权属性,检查是否
Request.IsAjaxRequest()
,并返回自定义 JSON 对象,而不是重定向到登录页面的默认行为(这是不可能发生的) 编写一个自定义授权属性,检查是否Request.IsAjaxRequest()
,并返回Yep, this is one of things i've always hated about Forms Authentication in ASP.NET - does not cater for AJAX authentication at all. Add IIS handling 401's into the mix, and it can be quite a pain.
There's a few ways to do this, none of them particulary "clean".
These include:
Set a ViewBag flag in the controller, which corresponds to
Request.IsAuthenticated
, then re-write the submit button click event to the login page if they're not authenticated.Make your AJAX action return
JsonResult
, which a property for "code". Where a code of 0 can be success, 1 can be unauthenticated, 2 can be some other data issue, etc. Then check for that code in thecomplete
$.ajax
callback and redirect to the login page.Check the
$.ajax
jqXHR
response object for a status code of403
, and redirect to the login page.Write a custom HTML helper for your submit button, which renders either a regular submit button, or a anchor tag which goes to the login page, depending on the authentication status.
Write a custom authorize attribute which checks if
Request.IsAjaxRequest()
, and returns a custom JSON object, instead of the default behaviour which is to redirect to the login page (which can't happen for AJAX requests).老实说,有点痛苦。在我看来,如果您使用的是联合身份,例如 Windows Identity Foundation 和/或 Azure AppFabric 访问控制服务,则更是如此。
您的 Ajax 调用无法处理重定向。
我的解决方案/建议不是使用 [Authorize] 标记 Ajax 调用的控制器操作方法,而是依赖于从具有 [Authorize] 的控制器操作插入到会话状态中的某些值的存在(通常是控制器)被调用以显示视图的操作方法)。您知道,除非用户经过身份验证(并且会话未超时),否则该值不可能进入会话状态。如果该值不存在,则对 Ajax 方法的调用将失败,并返回一个特定的 JSON 结果,您可以在客户端代码中妥善处理该结果。
在 Ajax 控制器方法上使用 [Authorize] 会导致奇怪的、通常是隐藏的错误(例如更新消失)。
It's a bit of a pain, to be honest. Even more so, in my opinion, if you're using Federated Identity, such as Windows Identity Foundation and/or Azure AppFabric Access Control Service.
Your Ajax calls can't handle the redirect.
My solution/suggestion is not to mark your Ajax-invoked controller action methods with [Authorize], but instead rely on the presence of some value that you insert into Session State from a controller action that does have an [Authorize] (typically the controller action method that was called to display the view). You know that the value can't have got into Session State unless the user was authenticated (and the session hasn't timed out). Fail the call to your Ajax method if this value isn't present, returning a specific JSON result that you can handle gracefully in your client-side code.
Using [Authorize] on an Ajax controller method causes weird, often hidden, errors (such as updates disappearing).