亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在ASP.NET MVC中重定向未經授權的控制器

在ASP.NET MVC中重定向未經授權的控制器

C#
楊__羊羊 2019-12-12 14:26:56
我在ASP.NET MVC中有一個控制器,但僅限于管理員角色:[Authorize(Roles = "Admin")]public class TestController : Controller{   ...如果沒有管理員角色的用戶導航到該控制器,則會看到空白屏幕。我想做的就是將他們重定向到View,上面寫著“您必須具有管理員角色才能訪問此資源”。我想到的一種方法是檢查IsUserInRole()上的每個操作方法,如果不起作用,則返回此信息視圖。但是,我必須將其放入每個會破壞DRY原理并且很麻煩維護的Action中。
查看完整描述

3 回答

?
吃雞游戲

TA貢獻1829條經驗 獲得超7個贊

您可以HandleUnauthorizedRequest在自定義中使用可覆蓋的內容AuthorizeAttribute


像這樣:


protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)

{

    // Returns HTTP 401 by default - see HttpUnauthorizedResult.cs.

    filterContext.Result = new RedirectToRouteResult(

    new RouteValueDictionary 

    {

        { "action", "YourActionName" },

        { "controller", "YourControllerName" },

        { "parameterName", "YourParameterValue" }

    });

}

您還可以執行以下操作:


private class RedirectController : Controller

{

    public ActionResult RedirectToSomewhere()

    {

        return RedirectToAction("Action", "Controller");

    }

}

現在,您可以通過HandleUnauthorizedRequest以下方式在您的方法中使用它:


filterContext.Result = (new RedirectController()).RedirectToSomewhere();


查看完整回答
反對 回復 2019-12-12
?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

“ tvanfosson”的代碼給了我“執行子請求時出錯”。我這樣更改了OnAuthorization:


public override void OnAuthorization(AuthorizationContext filterContext)

    {

        base.OnAuthorization(filterContext);


        if (!_isAuthorized)

        {

            filterContext.Result = new HttpUnauthorizedResult();

        }

        else if (filterContext.HttpContext.User.IsInRole("Administrator") || filterContext.HttpContext.User.IsInRole("User") ||  filterContext.HttpContext.User.IsInRole("Manager"))

        {

            // is authenticated and is in one of the roles 

            SetCachePolicy(filterContext);

        }

        else

        {

            filterContext.Controller.TempData.Add("RedirectReason", "You are not authorized to access this page.");

            filterContext.Result = new RedirectResult("~/Error");

        }

    }

這很好用,我在錯誤頁面上顯示了TempData。感謝“ tvanfosson”的代碼片段。我正在使用Windows身份驗證,_isAuthorized只是HttpContext.User.Identity.IsAuthenticated ...


查看完整回答
反對 回復 2019-12-12
  • 3 回答
  • 0 關注
  • 563 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號