aspnetcore 开发应具备基本功能
认证授权:需要加入controller的过滤器中
////// token认证验证过滤器 /// public class AuthFilter : IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) { var headers = context.HttpContext.Request.Headers; var keys = headers.Keys; if (keys.Contains("Token")) { // 到这里认为token验证通过 } else { context.Result = new JsonResult(new { Message = "未授权" }); } } }
全局异常:需要加入controller的过滤器中
////// 全局异常过滤器 /// public class GlobalExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { context.Result = new JsonResult(new { Ex = context.Exception.Message }); } }
认证通过后,用户上下文:需要提前注入IHttpContextAccessor,并且是单例模式。
////// 根据token封装用户上下文,注入其他业务层service /// public class UserContext { private string _user = null;// 似session用户信息 public UserContext(IHttpContextAccessor access) { var headers = access.HttpContext.Request.Headers; var keys = headers.Keys; if (keys.Contains("Token")) { _user = headers["Token"].ToString(); } } public string User { get { return _user; } } }
启动配置:
// Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(i => { i.SwaggerDoc("api", new Microsoft.OpenApi.Models.OpenApiInfo() { Title = "Api Document", Version = "" }); // 添加控制器层注释,true表示显示控制器注释 i.IncludeXmlComments(System.IO.Path.Combine(AppContext.BaseDirectory, $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml"), true); // 认证界面的定义 i.AddSecurityDefinition("Auth", new Microsoft.OpenApi.Models.OpenApiSecurityScheme { Name = "Token", In = Microsoft.OpenApi.Models.ParameterLocation.Header, Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey }); // 每次请求携带的参数 i.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement { { new Microsoft.OpenApi.Models.OpenApiSecurityScheme { Reference = new Microsoft.OpenApi.Models.OpenApiReference { Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme, Id = "Auth" } }, new List<string>() } }); }); services.AddControllers(i => { i.Filters.Add(typeof(GlobalExceptionFilter)); i.Filters.Add(typeof(AuthFilter)); }); services.AddSingleton(); services.AddScoped(typeof(DbContxt)); services.AddScoped(typeof(UserContext)); }
// Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.UseSwaggerUI(c => { var isShow = Configuration.GetSection("Swagger:IsShow").Value; var appName = Configuration.GetSection("Swagger:VirtualDir").Value; string jsonPath = "api/swagger.json"; if (isShow.Equals("1")) { jsonPath = $"/{appName}/swagger/" + jsonPath; } c.SwaggerEndpoint(jsonPath, "API"); }); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }