Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

c# - In MVC how can I use the controller to render a partial view only for approved users?

In MVC 5 I am attempting to use the controller to render a partial view only if the (Windows Authenticated) user belongs to one or more of a list of Active Directory groups. There are over 30 distinct groups I need to account for, so the "hello world" examples don't fit my needs. After playing scavenger hunt on the web, I managed to collect this much. No compile or runtime errors, but the content is showing for all users rather than the specific users. So the desired outcome is not yet achieved.

While I can achieve the desired outcome using if-then logic in the view, it creates a lot of unnecessary duplication and encourages spaghettification. So I'm trying to do this in the controller.

Summary of Desired Outcome:

When the user loads the viewpage, the partial view should only render if the Windows Authenticated user belongs to one or more of a list of groups defined in the controller action. If the user is not authorized, then the partial view is not included.

Controller Block:

[ChildActionOnly]
    [Authorize(Roles="Domain\GroupA,Domain\GroupB")]
    public ActionResult MonitorCSU()
    {   
        return PartialView("MonitorCSU");            
    }

View Block:

<div class="rowWithCols3">
@Html.Partial("MonitorCSU")

Unsuccessful Iterations:

  • In the controller block I tried (unsuccessfully) to use an if-then block, the else case being another partial view with no content.

    [ChildActionOnly]
    public ActionResult MonitorCSU() { if (User.IsInRole("DomainGroupA")) { return PartialView("_MonitorCSU"); } else { return PartialView("_Unauthorized"); } }

  • In Razor, I tried using HTML.Action but when I tried run the page the browser hung in an infinite loop.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@Html.Partial() returns a partial view without calling a controller method. In order to call your controller method, you need to use

@Html.Action("MonitorCSU")

or

@{ Html.RenderAction("MonitorCSU") }

Note this assumes that the MonitorCSU() method is in the same controller as the method that generates the main view (other wise you also need to include a parameter for the controller name)

Refer documentation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...