新建一個空的項目 新建好了空的項目以後,接著通過NuGet安裝一下三個包 Nancy Nancy.Hosting.Aspnet Nancy.ViewEnglines.Razor 然後在項目中添加Models,Module,Views三個文件夾,併在Models中添加UserModel類 然後往Mod ...
新建一個空的項目
新建好了空的項目以後,接著通過NuGet安裝一下三個包
- Nancy
- Nancy.Hosting.Aspnet
- Nancy.ViewEnglines.Razor
然後在項目中添加Models,Module,Views三個文件夾,併在Models中添加UserModel類
public string Username { get; set; } public UserModel(string username) { this.Username = username; }
然後往Module文件夾裡面添加MainModule類
Get("/", Lexan => { return View["index.cshtml"]; }); Get("/login", Lexan => { return View["login.cshtml",this.Request.Query.returnUrl]; });
再繼續添加SecureModule類,AnotherVerySecureModule類
public SecureModule():base("/secure") { this.RequiresAuthentication(); Get("/",Lexan=> { var model = new UserModel(this.Context.CurrentUser.Identity.Name); return View["secure.cshtml",model]; }); }
public AnotherVerySecureModule():base("/superSecure") { this.RequiresClaims(Lexan=>Lexan.Type==ClaimTypes.Role&&Lexan.Value=="SuperSecure"); Get("/",Lexan=> { var model = new UserModel(this.Context.CurrentUser.Identity.Name); return View["superSecure.cshtml",model]; }); }
根目錄添加AuthenticationBootstrapper類
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); pipelines.BeforeRequest += ctx => { var username = ctx.Request.Query.username; if (username.HasValue) { ctx.CurrentUser = new ClaimsPrincipal(new ClaimsIdentity(BuildClaims(username), "querystring")); } return null; }; pipelines.AfterRequest += ctx => { if (ctx.Response.StatusCode==HttpStatusCode.Unauthorized) { ctx.Response = new RedirectResponse("/login?retutnUrl="+ Uri.EscapeDataString(ctx.Request.Path)); } }; } private static IEnumerable<Claim> BuildClaims(string userName) { var claims = new List<Claim>(); if (String.Equals(userName,"Lexan",StringComparison.OrdinalIgnoreCase)) { claims.Add(new Claim(ClaimTypes.Role,"SuperSecure")); } return claims; }
繼續在Views里添加視圖index,login,secure,superSecure
再然後修改一下Web.config如下圖
運行如下圖
謝謝觀看!