手机网站如何优化,京东电子商务网站建设目的,dk域名网站,h5页面网站模板在.net framework 4.5架构下使用认证#xff08;Authentication#xff09;授权(Authorization)。IIS使用HttpModule进行认证#xff08;Authentication#xff09;#xff0c;我们可以选择自己实现认证方式并在web.config中配置#xff0c;当然也可以选择IIS默认提供的几… 在.net framework 4.5架构下使用认证Authentication授权(Authorization)。IIS使用HttpModule进行认证Authentication我们可以选择自己实现认证方式并在web.config中配置当然也可以选择IIS默认提供的几种实现这里不再继续展开讨论。 asp.net core默认提供了几种默认的实现方式包括IdentityFacebook, Google, Microsoft Account, Twitter 等等。这里介绍Basic Authentication认证方式。asp.net core的请求通道由一系列的请求委托组成一个一个顺序执行。实现Basic Authentication最简单的方式是添加一个中间件。新建文件BasicAuthenticationMiddlerwarepublic sealed class BasicAuthenticationMiddlerware { private readonly RequestDelegate _next; public BasicAuthenticationMiddlerware(RequestDelegate next) { _next next; } public async Task InvokeAsync(HttpContext context) { string authentication context.Request.Headers[Authorization]; if (authentication ! null authentication.Contains(Basic)) { //Extract credentials var usernamePasswordStr authentication.Trim().Split( )[1]; var userNamAndPasswordArr usernamePasswordStr.Split(:); if (userNamAndPasswordArr.Length ! 2) { context.Response.StatusCode 401; } var username userNamAndPasswordArr[0]; var password userNamAndPasswordArr[1]; /* * 根据用户账号密码验证用户有效性 * 如果有效 * 执行 await _next.Invoke(context); * 否则 * context.Response.StatusCode 401; */ if (true) { await _next.Invoke(context); } else { context.Response.StatusCode 401; } } else { context.Response.StatusCode 401; } } }完成中间件的定义以后在Startup.cs文件的Configure方法中注册中间件以开启验证。注意这里一定要添加在app.UseMvc()之前。app.UseMiddlewareBasicAuthenticationMiddlerware(); 或者通过添加IApplicationBuilder的扩张方法再用扩展方法进行注册。代码如下public static class BasicAuthenticationMiddlerwareExtension { public static IApplicationBuilder UseBasicAuthenticationMiddlerware( this IApplicationBuilder builder) { return builder.UseMiddlewareBasicAuthenticationMiddlerware(); } }Startup.cs的Configure的内容如下public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseBasicAuthenticationMiddlerware(); app.UseMvc();}启动WebApi。不添加头文件Authorization如预期返回401状态码。 添加头部信息如预期返回数据。 原文地址http://www.cnblogs.com/Zhang-Xiang/p/7536803.html.NET社区新闻深度好文微信中搜索dotNET跨平台或扫描二维码关注