ASP.NET MVC5中过滤器验证的改进

    ASP.NET MVC5包括了最近发布的Visual Studio 2013开发者预览版,使得开发者可以运用身份验证的过滤器,这样就为使用第三方组件或者定制的验证提供了方便。然而,这些过滤器之前被用来调用验证过滤器。

    为了创建一个验证过滤器,你需要创建一个C#ASP.NET项目并且从项目类型中选择MVC模式,Eric Vogel,高级软件工程师,Kunz,Leigh&Associates已经验证了通过使用一个已经创建的用户过滤器可以使未认证的用户跳转到登录页面。
    Eric创建了一个用户属性目录和一个叫做CustomAttribute的新类,它继承于ActionFilterAttribute和IAuthenticationFilter。
    public class BasicAuthAttribute: ActionFilterAttribute, IAuthenticationFilter
    当OnAuthentication()方法包括了IAuthenticationFilter接口时可以完成任何需要的验证,OnAuthenticatonChallenge方法根据用户的角色限制用户的访问权限。
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
    var user = filterContext.HttpContext.User;
    if (user == null || !user.Identity.IsAuthenticated)
    {
        filterContext.Result = new HttpUnauthorizedResult();
    }
}
    你可以通过Eric的博客访问源代码。测试BasicAuthAttribute类也非常简单,只需要将它添加到HomeController类中,然后打开文件添加下面一行代码:
using VSMMvc5AuthFilterDemo.CustomAttributes; 
    最后,在HomeController类使用用户属性如下所示:
[BasicAuthAttribute]
public class HomeController : Controller
 
饭后茶余翻译以为乐趣,若有误,恳请斧正!
posted @ 2013-09-12 07:24  浪屿  阅读(1847)  评论(0)    收藏  举报