Hide content in view mode based on controller authorization filters

Let's say I have a controller action that is limited only to specific users, for example:

[Authorize(Roles="somerole")]<br />
public ActionResult TestRestricted()  {            
    return View();
}

In a view that is publicly available to everyone, I have a link to the action above:

<%= Html.ActionLink("Click here!", "TestRestricted") %>

I would like to hide the link for everyone who is not allowed to perform the "TestRestricted" -action. Is there a way to check if the current user is allowed to use the appropriate action? Without defining any additional or duplicate access rules in addition to the authorization filter?

+3
source share
2 answers

MVC , .

, , . .

, Action HtmlHelper . , System.Web.Mvc.Html.

    public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string role)
    {
        MvcHtmlString link = new MvcHtmlString(string.Empty);

        if (htmlHelper.ViewContext.RequestContext.HttpContext.User.IsInRole(role))
        {
            link = htmlHelper.ActionLink(linkText, actionName);
        }

        return link;
    }

<%= Html.ActionLink("Click here!", "TestRestricted", "somerole") %>

, (). - , authorize .

+2

Source: https://habr.com/ru/post/1718447/


All Articles