【问题标题】:How can I authenticate the user within Json controller action?如何在 Json 控制器操作中对用户进行身份验证?
【发布时间】:2009-12-02 15:28:24
【问题描述】:

我有一个 .NET MVC 控制器操作,它将 JsonResult 返回到 YUI AsyncRequest 回调。 AsyncRequest 调用一切正常,“内容”模型数据已成功更新。我现在如何确保在发出 AsyncRequest 之前用户已登录?

通常我会使用 [Authorize] 属性,它会向我的 YUI AsyncRequest 返回一个错误,因为它需要一个 Json 结果。

我也尝试在 Action 中检查“User.Identity.IsAuthenticated”,但仍然没有爱。RedirectToRoute 似乎什么也没做。

我已经能够将指示用户需要登录的 Json 结果发送回 JS,但我宁愿让它将用户重定向到 LogOn 视图。

这是控制器动作:

[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!

【问题讨论】:

    标签: asp.net-mvc json yui


    【解决方案1】:

    你可以这样做:

    [JsonFilter(Param="content"), JsonDataType=typeof(Content)]
    public ActionResult SaveJson(Content content) 
    {
    
        if (!User.Identity.IsAuthenticated)
        {
            var urlHelper = new UrlHelper(ControllerContext.RequestContext);
            return Json(new {Result = "unauthenticated" , Url = urlHelper.Action("LogOn", "Account")});
        }
    
        contentRepository.Update(content);
        return Json(new {Result = "sucess"});
    }
    

    您将使用 urlHelper.Action("LogOn", "Account") 部分结果将位置更改为登录页面 (window.location.href = ...)。

    附加说明:您可以将urlHelper.Action("LogOn", "Account") 移动到您的视图中,作为回调函数的一部分。

    【讨论】:

    • 谢谢.. 我开始考虑在我的 JS 中使用 window.location,我喜欢你将 url 传回给它的想法,
    • @Skelly:请记住,您不必通过它,您可以在视图生成期间已经拥有它,这可能是更优选的方式。
    【解决方案2】:

    我认为语义上正确的做法是返回带有 401(未授权)状态码的 HTTP 响应,并让 js 决定如何响应。我对 YUI 不熟悉,但是在 jQuery 中你可以像这样设置错误回调函数...

    function BasicJSONPost(urlToPost, dataToSend, onSuccess) {
    $.ajax({
        url: urlToPost,
        data: dataToSend,
        dataType: "json",
        type: "POST",
        success: onSuccess,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            HandleAjaxError(XMLHttpRequest, textStatus, errorThrown);
        }
    });
    }
    
    function HandleAjaxError(XMLHttpRequest, textStatus, errorThrown) {
        if (XMLHttpRequest.status == 401) {
            window.location.href = '/account/login';
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-05
      • 2020-01-03
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 2021-11-30
      • 2012-05-06
      相关资源
      最近更新 更多