c# User.IsInRole Namespace

故事扮演 提交于 2020-01-01 06:53:59

问题


Note, I am using c# MVC 3, I am trying to use this within a class, NOT a controller.

I have the following at top of my program

    using System.Web.Security;

I tried to do the following but get the message:

The name 'User' does not exist in the current context.

Here is my partial code:

     using System.Web.Security;
     ....
     ....

     if (User.IsInRole("Admin"))  
     {

     }

I am thinking that is has to do something with the namespace but looking at the documentation, all I should need is System.Web.Security.


回答1:


Try first : while executing the view, check the following in controller HttpContext.Current.User.IsInRole("Admin") - this line check your value.

It should return a bool value if you have current HttpContext loaded.

Solution #2: Look at the default mvc3 project:

Context.User.IsInRole("Admin")

instead of Page.User.IsInRole("Admin").

In addition: you may check this post about how to set usage of roles - User.IsInRole(" ") without using Membership.

Look for the following usage with ASP.NET MVC Membership classes :

  • Membership and Authorization in ASP.Net MVC 3 Razor
  • SimpleMembership, Membership Providers, Universal Providers and the new ASP.NET 4.5 Web Forms and ASP.NET MVC 4 templates
  • Asp.net membership - how to determine programmatically is user is in role
  • ASP.NET MVC Membership Roles



回答2:


add using System.Web.Mvc; That should do it

So based on your comment, I'm going to assume you are working in a class that is not a Controller, but is inside your MVC project. So you should be able to do what you are attempting like so

if(HttpContext.Current.User.IsInRole("Admin"))
    {
      //...         
    }



回答3:


Use System.Web.HttpContext.Current.User.IsInRole("yourRole")

Hope it will help :)



来源:https://stackoverflow.com/questions/14246376/c-sharp-user-isinrole-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!