从Razor视图中获取Test IsAuthorization

时间:2015-11-26 09:50:16

标签: asp.net-mvc razor

简而言之,您如何检查剃须刀视图是否需要授权?

注意:@User.Identity.IsAuthenticated不会这样做。我对用户是否经过身份验证或授权不感兴趣 - 而是一个页面需要在“全局”(井布局)级别进行授权/身份验证。

假设有2个控制器,如下所示:

[Authorize]
public class SecretController : Controller
{
    [AllowAnonymous]
    public ActionResult SecretClue()
    {
        return View("oo lala");
    }

    public ActionResult Secret()
    {
        return View("Jane kissed ...");
    }
}


public class RecipesController : Controller
{
    public ActionResult RoastBoar()
    {
        return View("One wild boar...");
    }

    [Authorize]
    public ActionResult SecretSauce()
    {
        return View("Mustard, mixed with...");
    }
}

我如何从_Layout razor视图确定页面是否需要授权/身份验证,以便在显示<p>Remember SHHHH!</p>行时显示?

<!DOCTYPE html>
<html>
<head></head>

<body>
    <div>
        @if (ViewBag.IsAuthenticationRequired ?? false)
        {
            <p>Remember SHHHH!</p> 
        }
    </div>
</body>    

请不要问我为什么要这样做,如果可以,请回答这个问题。

1 个答案:

答案 0 :(得分:0)

经常发生这是一个解决方案,我欢迎其他更简单的解决方案......

public class IsAuthorizationRequiredFilter : IAuthorizationFilter
{
    public IsAuthorizationRequiredFilter() { }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        bool isAuthorizationRequired = !filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
                      && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
                      && (filterContext.ActionDescriptor.IsDefined(typeof(AuthorizeAttribute), inherit: true)
                      || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AuthorizeAttribute), inherit: true));

        filterContext.Controller.ViewBag.AuthenticationRequired = isAuthorizationRequired;
    }

    private bool IsValid(string key)
    {
        return true;
    }
}