如何使用MVC asp.net实现授权?
答案 0 :(得分:53)
使用授权属性
[Authorize]
public ActionResult MyAction()
{
//stuff
}
您也可以在控制器上使用它。也可以传入用户或角色。
如果你想要一些更多控制的东西,你可以试试像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;
}
}
答案 1 :(得分:4)
MVC有一个授权功能,使用ASP.NET MVC beta并从Visual Studio创建MVC项目,自动添加一个使用授权的控制器。有助于谷歌搜索的一件事是它是一个“过滤器”。因此,请尝试搜索“授权过滤器MVC”,任何预览4或更高版本都将有所帮助。
答案 2 :(得分:2)
我建议你看一下这篇文章: http://kbochevski.blogspot.com/2009/11/mvc-forms-authentication-and.html
今天帮助了我。
答案 3 :(得分:0)
默认情况下,您可以进行身份验证: http://mycodepad.wordpress.com/2014/03/17/mvc-secure-your-web-app/