如何在 Json 控制器操作中对用户进行身份验证?
我有一个 .NET MVC 控制器操作,它将 JsonResult 返回到 YUI AsyncRequest 回调。 AsyncRequest 调用一切正常,并且“内容”模型数据已成功更新。我现在如何确保用户在发出 AsyncRequest 之前已登录?
通常我会使用 [Authorize] 属性,它会向我的 YUI AsyncRequest 返回错误,因为它需要 Json 结果。
我也尝试过在操作中检查“User.Identity.IsAuthenticated”,但仍然没有爱。RedirectToRoute 似乎什么也没做。
我已经能够将 Json 结果发送回 JS,指示用户需要登录,但我宁愿让它将用户重定向到登录视图。
这是控制器操作:
[JsonFilter(Param="content"), JsonDataType=typeof(Content)]
public ActionResult SaveJson(Content content)
{
if (!User.Identity.IsAuthenticated)
RedirectToRoute(new { Action="LogOn", Controller="Account"});
contentRepository.Update(content);
return Json(new {Result = "sucess"});
}
TIA!
I have a .NET MVC controller action that returns a JsonResult to a YUI AsyncRequest callback. All is working fine with the AsyncRequest call and the "Content" model data is successfully updated. How can I now assure that the user is logged before the AsyncRequest is made?
Normally I would use the [Authorize] attribute which returns an error back to my YUI AsyncRequest since it is expecting a Json result.
I've also tried checking "User.Identity.IsAuthenticated" wihtin the Action but still no love.. The RedirectToRoute seems to do nothing.
I have been able to send a Json result back to JS that indicated the user needs to login, but I'd rather have it redirect the user to the LogOn view.
Here is the Controller action:
[JsonFilter(Param="content"), JsonDataType=typeof(Content)]
public ActionResult SaveJson(Content content)
{
if (!User.Identity.IsAuthenticated)
RedirectToRoute(new { Action="LogOn", Controller="Account"});
contentRepository.Update(content);
return Json(new {Result = "sucess"});
}
TIA!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以执行以下操作:
您将使用结果的
urlHelper.Action("LogOn", "Account")
部分将位置更改为登录页面 (window.location.href = ... )。
附加说明:您可以将
urlHelper.Action("LogOn", "Account")
移动到您的视图,作为回调函数的一部分。You can do something like:
You will use
urlHelper.Action("LogOn", "Account")
part of result to change location to login page (window.location.href = ...
).Additional note: You can move
urlHelper.Action("LogOn", "Account")
to your view, as a part of your callback function.我认为语义上正确的做法是返回带有 401(未经授权)状态代码的 HTTP 响应,并让 js 决定如何响应。我不熟悉 YUI,但在 jQuery 中你可以像这样设置错误回调函数......
I think the semantically correct thing to do is return an HTTP response with a 401 (Unauthorized) status code and let the js decide how to respond. I'm not familiar with YUI, but in jQuery you can setup an error callback function like so...