ASP.NET MVC Authorization

本秂侑毒 提交于 2019-11-26 09:27:14

问题


How do I achieve authorization with MVC asp.net?


回答1:


Use the Authorize attribute

[Authorize]
public ActionResult MyAction()
{
   //stuff
}

You can also use this on the controller. Can pass in users or roles too.

If you want something with a little more control, you could try something like this.

 public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string[] users = Users.Split(',');

            if (!httpContext.User.Identity.IsAuthenticated)
                return false;

            if (users.Length > 0 &&
                !users.Contains(httpContext.User.Identity.Name,
                    StringComparer.OrdinalIgnoreCase))
                return false;

            return true;
        }
    }



回答2:


There is an Authorization feature with MVC, using ASP.NET MVC beta and creating the MVC project from Visual Studio, automatically adds a controller that used authorization. One thing that will help with your google search, is that it is a "filter". So try searching on "Authorization Filter MVC" and anything preview 4 or greater will help.




回答3:


I would recommend to take a look at this article: http://kbochevski.blogspot.com/2009/11/mvc-forms-authentication-and.html

It helped me today.




回答4:


This is how you can have authentication by default: http://mycodepad.wordpress.com/2014/03/17/mvc-secure-your-web-app/



来源:https://stackoverflow.com/questions/329658/asp-net-mvc-authorization

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