隨着近幾年先後端分離、微服務等模式的興起,.Net Core也似有如火如荼之勢 ,自16年發佈第一個版本到19年末的3.1 LTS版本,以及將發佈的.NET 5,.NET Core一路更迭,在部署和開發工具上也都支持了跨平臺應用。一直對.Net Core有所關注,但未涉及太多實際應用,通過一番學習和了解後,因而分享出來。本文主要以.Net Core Web API爲例,講述.Net Core的基本應用及注意事項,對於想經過WebAPI搭建接口應用的開發者,應該能提供一個系統的輪廓和認識,同時和更多的.Net Core開發者交流互動,探本勘誤,增強對知識的理解,並幫助更多的人。本文以貼近基本的實際操做爲主,部分概念或基礎步驟再也不贅述,文中若有疏漏,還望不吝斧正。javascript
開發環境:Visual Studio 2019css
爲解決先後端苦於接口文檔與實際不一致、維護和更新文檔的耗時費力等問題,swagger應運而生,同時也解決了接口測試問題。話很少說,直接說明應用步驟。html
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1", Description = "API文檔描述", Contact = new OpenApiContact { Email = "5007032@qq.com", Name = "測試項目", //Url = new Uri("http://t.abc.com/") }, License = new OpenApiLicense { Name = "BROOKE許可證", //Url = new Uri("http://t.abc.com/") } }); });
Startup類的Configure方法添加以下代碼:
前端
//配置Swagger app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); c.RoutePrefix = "api";// 若是設爲空,訪問路徑就是根域名/index.html,設置爲空,表示直接在根域名訪問;想換一個路徑,直接寫名字便可,好比直接寫c.RoutePrefix = "swagger"; 則訪問路徑爲 根域名/swagger/index.html });
Ctrl+F5進入瀏覽,按上述配置修改路徑爲:http://localhost:***/api/index.html,便可看到Swagger頁面:java
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1", Description = "API文檔描述", Contact = new OpenApiContact { Email = "5007032@qq.com", Name = "測試項目", //Url = new Uri("http://t.abc.com/") }, License = new OpenApiLicense { Name = "BROOKE許可證", //Url = new Uri("http://t.abc.com/") } }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); });
上述代碼經過反射生成與Web API項目相匹配的XML文件名,AppContext.BaseDirectory屬性用於構造 XML 文件的路徑,關於OpenApiInfo內的配置參數用於文檔的一些描述,在此不做過多說明。
而後右鍵Web API項目、屬性、生成,配置XML文檔的輸出路徑,以及取消沒必要要的XML註釋警告提醒(增長1591):
jquery
var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//獲取應用程序所在目錄 var xmlPath = Path.Combine(basePath, "CoreAPI_Demo.xml"); c.IncludeXmlComments(xmlPath, true);
同時,調整項目生成的XML文檔文件路徑爲:..\CoreAPI_Demo\CoreAPI_Demo.xmlgit
{ "$schema": "http://json.schemastore.org/launchsettings.json", "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:7864", "sslPort": 0 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "api", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "CoreApi_Demo": { "commandName": "Project", "launchBrowser": true, "launchUrl": "api", "applicationUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
以讀取appsettings.json文件爲例,固然你也定義其餘名稱的.json文件進行讀取,讀取方式一致,該文件相似於Web.config文件。爲方便示例,定義appsettings.json文件內容以下:github
{ "ConnString": "Data Source=(local);Initial Catalog=Demo;Persist Security Info=True;User ID=DemoUser;Password=123456;MultipleActiveResultSets=True;", "ConnectionStrings": { "MySQLConnection": "server=127.0.0.1;database=mydemo;uid=root;pwd=123456;charset=utf8;SslMode=None;" }, "SystemConfig": { "UploadFile": "/Files", "Domain": "http://localhost:7864" }, "JwtTokenConfig": { "Secret": "fcbfc8df1ee52ba127ab", "Issuer": "abc.com", "Audience": "Brooke.WebApi", "AccessExpiration": 30, "RefreshExpiration": 60 }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //讀取方式一 var ConnString = Configuration["ConnString"]; var MySQLConnection = Configuration.GetSection("ConnectionStrings")["MySQLConnection"]; var UploadPath = Configuration.GetSection("SystemConfig")["UploadPath"]; var LogDefault = Configuration.GetSection("Logging").GetSection("LogLevel")["Default"]; //讀取方式二 var ConnString2 = Configuration["ConnString"]; var MySQLConnection2 = Configuration["ConnectionStrings:MySQLConnection"]; var UploadPath2 = Configuration["SystemConfig:UploadPath"]; var LogDefault2 = Configuration["Logging:LogLevel:Default"]; } }
以上介紹了2種讀取配置信息的方式,若是要在Controller內使用,相似地,進行注入並調用以下:web
public class ValuesController : ControllerBase { private IConfiguration _configuration; public ValuesController(IConfiguration configuration) { _configuration = configuration; } // GET: api/<ValuesController> [HttpGet] public IEnumerable<string> Get() { var ConnString = _configuration["ConnString"]; var MySQLConnection = _configuration.GetSection("ConnectionStrings")["MySQLConnection"]; var UploadPath = _configuration.GetSection("SystemConfig")["UploadPath"]; var LogDefault = _configuration.GetSection("Logging").GetSection("LogLevel")["Default"]; return new string[] { "value1", "value2" }; } }
以SystemConfig節點爲例,定義類以下:ajax
public class SystemConfig { public string UploadPath { get; set; } public string Domain { get; set; } }
調整代碼以下:
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.Configure<SystemConfig>(Configuration.GetSection("SystemConfig")); } }
而後Controller內進行注入調用:
[Route("api/[controller]/[action]")] [ApiController] public class ValuesController : ControllerBase { private SystemConfig _sysConfig; public ValuesController(IOptions<SystemConfig> sysConfig) { _sysConfig = sysConfig.Value; } [HttpGet] public IEnumerable<string> GetSetting() { var UploadPath = _sysConfig.UploadPath; var Domain = _sysConfig.Domain; return new string[] { "value1", "value2" }; } }
定義相關靜態類以下:
public static class MySettings { public static SystemConfig Setting { get; set; } = new SystemConfig(); }
調整Startup類構造函數以下:
public Startup(IConfiguration configuration, IWebHostEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); Configuration = builder.Build(); //Configuration = configuration; configuration.GetSection("SystemConfig").Bind(MySettings.Setting);//綁定靜態配置類 }
接下來,諸如直接使用:MySettings.Setting.UploadPath 便可調用。
接口通常少不了文件上傳,相比.net framework框架下webapi經過byte數組對象等複雜方式進行文件上傳,.Net Core WebApi有了很大變化,其定義了新的IFormFile對象來接收上傳文件,直接上Controller代碼:
[Route("api/[controller]/[action]")] [ApiController] public class UploadController : ControllerBase { private readonly IWebHostEnvironment _env; public UploadController(IWebHostEnvironment env) { _env = env; } public ApiResult UploadFile(List<IFormFile> files) { ApiResult result = new ApiResult();
//注:參數files對象去也能夠經過換成: var files = Request.Form.Files;來獲取
if (files.Count <= 0) { result.Message = "上傳文件不能爲空"; return result; } #region 上傳 List<string> filenames = new List<string>(); var webRootPath = _env.WebRootPath; var rootFolder = MySettings.Setting.UploadPath; var physicalPath = $"{webRootPath}/{rootFolder}/"; if (!Directory.Exists(physicalPath)) { Directory.CreateDirectory(physicalPath); } foreach (var file in files) { var fileExtension = Path.GetExtension(file.FileName);//獲取文件格式,拓展名 var saveName = $"{rootFolder}/{Path.GetRandomFileName()}{fileExtension}"; filenames.Add(saveName);//相對路徑 var fileName = webRootPath + saveName; using FileStream fs = System.IO.File.Create(fileName); file.CopyTo(fs); fs.Flush(); } #endregion result.IsSuccess = true; result.Data["files"] = filenames; return result; } }
接下來經過前端調用上述上傳接口,在項目根目錄新建wwwroot目錄(.net core webapi內置目錄 ),添加相關js文件包,而後新建一個index.html文件,內容以下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> </style> <script src="res/scripts/jquery-1.10.2.min.js"></script> <script src="res/scripts/jquery.form.js"></script> <script type="text/javascript"> //方法1 function AjaxUploadfile() { var upload = $("#files").get(0); var files = upload.files; var data = new FormData(); for (var i = 0; i < files.length; i++) { data.append("files", files[i]); } //此處data的構建也能夠換成:var data = new FormData(document.getElementById("myform")); $.ajax({ type: "POST", url: "/api/upload/uploadfile", contentType: false, processData: false, data: data, success: function (result) { alert("success"); $.each(result.data.files, function (i, filename) { $("#filePanel").append('<p>' + filename + '</p>'); }); }, error: function () { alert("上傳文件錯誤"); } }); } //方法2 function AjaxUploadfile2() { $("#myform").ajaxSubmit({ success: function (result) { if (result.isSuccess) { $.each(result.data.files, function (i, filename) { $("#filePanel").append('<p>' + filename + '</p>'); }); } else { alert(result.message); } } }); } </script> </head> <body> <form id="myform" method="post" action="/api/upload/uploadfile" enctype="multipart/form-data"> <input type="file" id="files" name="files" multiple /> <br /><br /> <input type="button" value="FormData Upload" onclick="AjaxUploadfile();" /><br /><br /> <input type="button" value="ajaxSubmit Upload" onclick="AjaxUploadfile2();" /><br /><br /> <div id="filePanel"></div> </form> <script type="text/javascript"> $(function () { }); </script> </body> </html>
上述經過構建FormData和ajaxSubmit兩種方式進行上傳,須要注意的是contentType和processData兩個參數的設置;另外容許一次上傳多個文件,需設置multipart屬性。
在訪問wwwroot下的靜態文件以前,必須先在Startup類的Configure方法下進行註冊:
public void Configure(IApplicationBuilder app) { app.UseStaticFiles();//用於訪問wwwroot下的文件 }
啓動項目,經過訪問路徑:http://localhost:***/index.html,進行上傳測試,成功後,將在wwwroot下的Files目錄下看到上傳的文件。
爲了方便先後端使用約定好的數據格式,一般咱們會定義統一的數據返回,其包括是否成功、返回狀態、具體數據等;爲便於說明,定義一個數據返回類以下:
public class ApiResult { public bool IsSuccess { get; set; } public string Message { get; set; } public string Code { get; set; } public Dictionary<string, object> Data { get; set; } = new Dictionary<string, object>(); }
這樣,咱們將每個action接口操做封裝爲ApiResult格式進行返回。新建一個ProductController示例以下:
[Produces("application/json")] [Route("api/[controller]")] [ApiController] public class ProductController : ControllerBase { [HttpGet] public ApiResult Get() { var result = new ApiResult(); var rd = new Random(); result.Data["dataList"] = Enumerable.Range(1, 5).Select(index => new { Name = $"商品-{index}", Price = rd.Next(100, 9999) }); result.IsSuccess = true; return result; } }
如此,即完成的數據返回的統一。
.Net Core Web Api默認以首字母小寫的類駝峯式命名返回,但遇到DateTime類型的數據,會返回T格式時間,如要解決T時間格式,定義一個時間格式轉換類以下:
public class DatetimeJsonConverter : JsonConverter<DateTime> { public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { if (DateTime.TryParse(reader.GetString(), out DateTime date)) return date; } return reader.GetDateTime(); } public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss")); } }
而後在Startup類的ConfigureServices中調整services.AddControllers代碼以下:
services.AddControllers() .AddJsonOptions(configure => { configure.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter()); });
模型驗證在ASP.NET MVC已存在,使用方式基本一致。指對向接口提交過來的數據進行參數校驗,包括必填項、數據格式、字符長度、範圍等等。通常的,咱們會將POST提交過來的對象定義爲一個實體類進行接收,譬如定義一個註冊類以下:
public class RegisterEntity { /// <summary> /// 手機號 /// </summary> [Display(Name = "手機號")] [Required(ErrorMessage = "{0}不能爲空")] [StringLength(11, ErrorMessage = "{0}最多{1}個字符")] public string Mobile { get; set; } /// <summary> /// 驗證碼 /// </summary> [Display(Name = "驗證碼")] [Required(ErrorMessage = "{0}不能爲空")] [StringLength(6, ErrorMessage = "{0}最多{1}個字符")] public string Code { get; set; } /// <summary> /// 密碼 /// </summary> [Display(Name = "密碼")] [Required(ErrorMessage = "{0}不能爲空")] [StringLength(16, ErrorMessage = "{0}最多{1}個字符")] public string Pwd { get; set; } }
Display標識提示字段的名稱,Required表示必填,StringLength限制字段的長度,固然還有其餘一些內置特性,具體可參考官方文檔,列舉一些常見的驗證特性以下:
上述說明了基本的模型驗證使用方法,以這種方式,同時結合T4模板,經過表對象生成模型驗證明體,省卻了在action中編寫大量驗證代碼的工做。固然,一些必要的較爲複雜的驗證,或結合數據庫操做的驗證,則單獨寫到action或其餘應用模塊中。
那麼上述模型驗證在Web API中是怎麼工做的呢?在Startup類的ConfigureServices添加以下代碼:
//模型參數驗證 services.Configure<ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = (context) => { var error = context.ModelState.FirstOrDefault().Value; var message = error.Errors.FirstOrDefault(p => !string.IsNullOrWhiteSpace(p.ErrorMessage))?.ErrorMessage; return new JsonResult(new ApiResult { Message = message }); }; });
添加註冊示例Action代碼:
/// <summary> /// 註冊 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] public async Task<ApiResult> Register(RegisterEntity model) { ApiResult result = new ApiResult(); var _code = CacheHelper.GetCache(model.Mobile); if (_code == null) { result.Message = "驗證碼過時或不存在"; return result; } if (!model.Code.Equals(_code.ToString())) { result.Message = "驗證碼錯誤"; return result; } /** 相關邏輯代碼 **/ return result; }
如此,經過配置ApiBehaviorOptions的方式,並讀取驗證錯誤信息的第一條信息並返回,即完成了Web API中Action對請求參數的驗證工做,關於錯誤信息Message的返回,也可略做封裝,在此略。
雖然.Net Core WebApi有自帶的日誌管理功能,但不必定能較容易地知足咱們的需求,一般會採用第三方日誌框架,典型的如:NLog、Log4Net,簡單介紹NLog日誌組件的使用;
① 經過NuGet安裝包:NLog.Web.AspNetCore,當前項目版本4.9.2;
② 項目根目錄新建一個NLog.config文件,關鍵NLog.config的其餘詳細配置,可參考官方文檔,這裏做簡要配置以下;
<?xml version="1.0" encoding="utf-8"?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="NlogRecords.log"> <!--Nlog內部日誌記錄爲Off關閉--> <extensions> <add assembly="NLog.Web.AspNetCore" /> </extensions> <targets> <target name="log_file" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} | ${level:uppercase=false} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" /> </targets> <rules> <!--跳過全部級別的Microsoft組件的日誌記錄--> <logger name="Microsoft.*" final="true" /> <!--<logger name="logdb" writeTo="log_database" />--> <logger name="*" minlevel="Trace" writeTo="log_file" /> </rules> </nlog> <!--https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3-->
③ 調整Program.cs文件以下;
public class Program { public static void Main(string[] args) { //CreateHostBuilder(args).Build().Run(); var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { logger.Debug("init main"); CreateHostBuilder(args).Build().Run(); } catch (Exception exception) { //NLog: catch setup errors logger.Error(exception, "Stopped program because of exception"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }).ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }).UseNLog();//依賴注入Nlog; }
其中Main函數裏的捕獲異常代碼配置省略也是能夠的,CreateHostBuilder下的UseNLog爲必設項。
Controller經過注入調用以下:
public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { _logger.LogInformation("測試一條日誌"); var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); }
本地測試後,便可在debug下看到logs目錄下生成的日誌文件。
使用.Net Core少不了和依賴注入打交道,這也是.Net Core的設計思想之一,關於什麼是依賴注入(DI),以及爲何要使用依賴注入,這裏再也不贅述,先來看一個簡單示例的依賴注入。
public interface IProductRepository { IEnumerable<Product> GetAll(); } public class ProductRepository : IProductRepository
{ public IEnumerable<Product> GetAll()
{ } }
Startup類進行註冊:
public void ConfigureServices(IServiceCollection services) { services.AddScoped<IProductRepository, ProductRepository>(); }
請求 IProductRepository 服務並用於調用 GetAll 方法:
public class ProductController : ControllerBase { private readonly IProductRepository _productRepository;
public ProductController(IProductRepository productRepository)
{ _productRepository = productRepository;
} public IEnumerable<Product> Get()
{ return _productRepository.GetAll();
} }
經過使用DI模式,來實現IProductRepository 接口。其實前述已屢次出現經過構造函數進行注入調用的示例。
services.AddScoped<IMyDependency, MyDependency>(); services.AddTransient<IMyDependency, MyDependency>(); services.AddSingleton<IMyDependency, MyDependency>();
這裏,須要根據具體的業務邏輯場景需求選擇注入相應的生命週期服務。
實際應用中,咱們會有不少個服務須要註冊到ConfigureServices內,一個個寫入顯然繁瑣,並且容易忘記漏寫,通常地,咱們可能會想到利用反射進行批量注入,並經過擴展的方式進行注入,譬如:
public static class AppServiceExtensions { /// <summary> /// 註冊應用程序域中的服務 /// </summary> /// <param name="services"></param> public static void AddAppServices(this IServiceCollection services) { var ts = System.Reflection.Assembly.Load("CoreAPI.Data").GetTypes().Where(s => s.Name.EndsWith("Repository") || s.Name.EndsWith("Service")).ToArray(); foreach (var item in ts.Where(s => !s.IsInterface)) { var interfaceType = item.GetInterfaces(); foreach (var typeArray in interfaceType) { services.AddTransient(typeArray, item); } } } }
public void ConfigureServices(IServiceCollection services) { services.AddAppServices();//批量註冊服務 }
誠然,這樣配合系統自帶DI注入是能完成咱們的批量注入需求的。但其實也有更多選擇,來幫咱們簡化DI註冊,譬如選擇其餘第三方組件:Scrutor、Autofac…
Scrutor是基於微軟注入組件的一個擴展庫,簡單示例以下:
services.Scan(scan => scan .FromAssemblyOf<Startup>() .AddClasses(classes => classes.Where(s => s.Name.EndsWith("Repository") || s.Name.EndsWith("Service")))
.AsImplementedInterfaces() .WithTransientLifetime() );
以上代碼經過Scan方式批量註冊了以Repository、Service結尾的接口服務,其生命週期爲Transient,該方式等同於前述的以反射方式的批量註冊服務。
關於Scrutor的其餘用法,你們能夠參見官方文檔,這裏只作下引子。
通常狀況下,使用MS自帶的DI或採用Scrutor,便可知足實際須要,若是有更高的應用需求,如要求屬性注入、甚至接管或取代MS自帶的DI,那麼你能夠選擇Autofac,關於Autofac的具體使用,在此不做詳敘。
按官方說明,開發人員需合理說用緩存,以及限制緩存大小,Core運行時不會根據內容壓力限制緩存大小。對於使用方式,依舊仍是先行註冊,而後控制器調用:
public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache();//緩存中間件 }
public class ProductController : ControllerBase { private IMemoryCache _cache; public ProductController(IMemoryCache memoryCache) { _cache = memoryCache; } [HttpGet] public DateTime GetTime() { string key = "_timeKey"; // Look for cache key. if (!_cache.TryGetValue(key, out DateTime cacheEntry)) { // Key not in cache, so get data. cacheEntry = DateTime.Now; // Set cache options. var cacheEntryOptions = new MemoryCacheEntryOptions() // Keep in cache for this time, reset time if accessed. .SetSlidingExpiration(TimeSpan.FromSeconds(3)); // Save data in cache. _cache.Set(key, cacheEntry, cacheEntryOptions); } return cacheEntry; } }
上述代碼緩存了一個時間,並設置了滑動過時時間(指最後一次訪問後的過時時間)爲3秒;若是須要設置絕對過時時間,將SetSlidingExpiration 改成SetAbsoluteExpiration便可。瀏覽刷新,每3秒後時間將更新。
附一個封裝好的Cache類以下:
public class CacheHelper { public static IMemoryCache _memoryCache = new MemoryCache(new MemoryCacheOptions()); /// <summary> /// 緩存絕對過時時間 /// </summary> ///<param name="key">Cache鍵</param> ///<param name="value">緩存的值</param> ///<param name="minute">minute分鐘後絕對過時</param> public static void SetChache(string key, object value, int minute) { if (value == null) return; _memoryCache.Set(key, value, new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromMinutes(minute))); } /// <summary> /// 緩存相對過時,最後一次訪問後minute分鐘後過時 /// </summary> ///<param name="key">Cache鍵</param> ///<param name="value">緩存的值</param> ///<param name="minute">滑動過時分鐘</param> public static void SetChacheSliding(string key, object value, int minute) { if (value == null) return; _memoryCache.Set(key, value, new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(minute))); } /// <summary> ///設置緩存,若是不主動清空,會一直保存在內存中. /// </summary> ///<param name="key">Cache鍵值</param> ///<param name="value">給Cache[key]賦的值</param> public static void SetChache(string key, object value) { _memoryCache.Set(key, value); } /// <summary> ///清除緩存 /// </summary> ///<param name="key">cache鍵</param> public static void RemoveCache(string key) { _memoryCache.Remove(key); } /// <summary> ///根據key值,返回Cache[key]的值 /// </summary> ///<param name="key"></param> public static object GetCache(string key) { //return _memoryCache.Get(key); if (key != null && _memoryCache.TryGetValue(key, out object val)) { return val; } else { return default; } } /// <summary> /// 經過Key值返回泛型對象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public static T GetCache<T>(string key) { if (key != null && _memoryCache.TryGetValue<T>(key, out T val)) { return val; } else { return default; } } }
這裏主要針對全局異常進行捕獲處理並記錄日誌,並以統一的json格式返回給接口調用者;說異常處理前先提下中間件,關於什麼是中間件,在此不在贅述,一箇中間件其基本的結構以下:
public class CustomMiddleware { private readonly RequestDelegate _next; public CustomMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext httpContext) { await _next(httpContext); } }
下面咱們定義本身的全局異常處理中間件,代碼以下:
public class CustomExceptionMiddleware { private readonly RequestDelegate _next; private readonly ILogger<CustomExceptionMiddleware> _logger; public CustomExceptionMiddleware(RequestDelegate next, ILogger<CustomExceptionMiddleware> logger) { _next = next; _logger = logger; } public async Task Invoke(HttpContext httpContext) { try { await _next(httpContext); } catch (Exception ex) { _logger.LogError(ex,"Unhandled exception..."); await HandleExceptionAsync(httpContext, ex); } } private Task HandleExceptionAsync(HttpContext httpContext, Exception ex) { var result = JsonConvert.SerializeObject(new { isSuccess = false, message = ex.Message }); httpContext.Response.ContentType = "application/json;charset=utf-8"; return httpContext.Response.WriteAsync(result); } } /// <summary> /// 以擴展方式添加中間件 /// </summary> public static class CustomExceptionMiddlewareExtensions { public static IApplicationBuilder UseCustomExceptionMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<CustomExceptionMiddleware>(); } }
而後在Startup類的Configure方法裏添加上述擴展的中間件,見加粗部分:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //全局異常處理 app.UseCustomExceptionMiddleware(); }
在HandleExceptionAsync方法中,爲方便開發和測試,這裏將系統的錯誤返回給了接口調用者,實際生產環境中可統一返回固定的錯誤Message消息。
關於http狀態碼,常見的如正常返回的200,其餘40一、40三、40四、502等等等等,由於系統有時候並不老是返回200成功,對於返回非200的異常狀態碼,WebApi也要作到相應的處理,以便接口調用者能正確接收,譬如緊接下來的JWT認證,當認證令牌過時或沒有權限時,系統實際會返回40一、403,但接口並不提供有效的可接收的返回,所以,這裏列舉一些常見的異常狀態碼,並以200方式提供給接口調用者,在Startup類的Configure方法裏添加代碼以下:
app.UseStatusCodePages(async context => { //context.HttpContext.Response.ContentType = "text/plain"; context.HttpContext.Response.ContentType = "application/json;charset=utf-8"; int code = context.HttpContext.Response.StatusCode; string message = code switch { 401 => "未登陸", 403 => "訪問拒絕", 404 => "未找到", _ => "未知錯誤", }; context.HttpContext.Response.StatusCode = StatusCodes.Status200OK; await context.HttpContext.Response.WriteAsync(Newtonsoft.Json.JsonConvert.SerializeObject(new { isSuccess = false, code, message })); });
代碼很簡單,這裏使用系統自帶的異常處理中間件UseStatusCodePages,固然,你還能夠自定義過濾器處理異常,不過不推薦,簡單高效直接纔是須要的。
關於.NET Core的異常處理中間件,還有其餘諸如 UseExceptionHandler、UseStatusCodePagesWithRedirects等等,不一樣的中間件有其適用的環境,有的可能更適用於MVC或其餘應用場景上,找到合適的便可。
題外話:你們也能夠將UseStatusCodePages處理異常狀態碼的操做封裝到前述的全局異常處理中間件中。
關於什麼是JWT,在此不做贅述。實際應用中,爲了部分接口的安全性,譬如須要身份認證才能訪問的接口資源,對於Web API而言,通常會採用token令牌進行認證,服務端結合緩存來實現。
那爲何要選擇JWT認證呢?緣由無外乎如下:服務端不進行保存、無狀態、適合移動端、適合分佈式、標準化等等。關於JWT的使用以下:
經過NuGget安裝包:Microsoft.AspNetCore.Authentication.JwtBearer,當前示例版本3.1.5;
ConfigureServices進行注入,默認以Bearer命名,這裏你也能夠改爲其餘名字,保持先後一致便可,注意加粗部分,代碼以下:
appsettings.json添加JWT配置節點(見前述【配置文件】),添加JWT相關認證類:
public static class JwtSetting { public static JwtConfig Setting { get; set; } = new JwtConfig(); } public class JwtConfig { public string Secret { get; set; } public string Issuer { get; set; } public string Audience { get; set; } public int AccessExpiration { get; set; } public int RefreshExpiration { get; set; } }
採用前述綁定靜態類的方式讀取JWT配置,並進行注入:
public Startup(IConfiguration configuration, IWebHostEnvironment env) { //Configuration = configuration; var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); Configuration = builder.Build(); configuration.GetSection("SystemConfig").Bind(MySettings.Setting);//綁定靜態配置類 configuration.GetSection("JwtTokenConfig").Bind(JwtSetting.Setting);//同上 } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { #region JWT認證注入 JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); services.AddAuthentication("Bearer") .AddJwtBearer("Bearer", options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = JwtSetting.Setting.Issuer, ValidAudience = JwtSetting.Setting.Audience, IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(JwtSetting.Setting.Secret)) }; }); #endregion }
給Swagger添加JWT認證支持,完成後,Swagger頁面會出現鎖的標識,獲取token後填入Value(Bearer token形式)項進行Authorize登陸便可,Swagger配置JWT見加粗部分:
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1", Description = "API文檔描述", Contact = new OpenApiContact { Email = "5007032@qq.com", Name = "測試項目", //Url = new Uri("http://t.abc.com/") }, License = new OpenApiLicense { Name = "BROOKE許可證", //Url = new Uri("http://t.abc.com/") } }); // 爲 Swagger JSON and UI設置xml文檔註釋路徑 //var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//獲取應用程序所在目錄(不受工做目錄影響) //var xmlPath = Path.Combine(basePath, "CoreAPI_Demo.xml"); //c.IncludeXmlComments(xmlPath, true); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); #region JWT認證Swagger受權 c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT受權(數據將在請求頭header中進行傳輸) 直接在下框中輸入Bearer {token}(中間是空格)", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, BearerFormat = "JWT", Scheme = "Bearer" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new string[] { } } }); #endregion });
Starup類添加Configure註冊,注意,需放到 app.UseAuthorization();前面:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseAuthentication();//jwt認證 app.UseAuthorization(); }
這樣,JWT就基本配置完畢,接下來實施認證登陸和受權,模擬操做以下:
[HttpPost] public async Task<ApiResult> Login(LoginEntity model) { ApiResult result = new ApiResult(); //驗證用戶名和密碼 var userInfo = await _memberService.CheckUserAndPwd(model.User, model.Pwd); if (userInfo == null) { result.Message = "用戶名或密碼不正確"; return result; } var claims = new Claim[] { new Claim(ClaimTypes.Name,model.User), new Claim(ClaimTypes.Role,"User"), new Claim(JwtRegisteredClaimNames.Sub,userInfo.MemberID.ToString()), }; var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(JwtSetting.Setting.Secret)); var expires = DateTime.Now.AddDays(1); var token = new JwtSecurityToken( issuer: JwtSetting.Setting.Issuer, audience: JwtSetting.Setting.Audience, claims: claims, notBefore: DateTime.Now, expires: expires, signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)); //生成Token string jwtToken = new JwtSecurityTokenHandler().WriteToken(token); //更新最後登陸時間 await _memberService.UpdateLastLoginTime(userInfo.MemberID); result.IsSuccess= 1; result.ResultData["token"] = jwtToken; result.Message = "受權成功!"; return result; }
上述代碼模擬登陸操做(帳號密碼登陸,成功後設置有效期一天),生成token並返回,前端調用者拿到token後以諸如localstorage方式進行存儲,調取受權接口時,添加該token到header(Bearer token)進行接口請求。接下來,給須要身份受權的Controller或Action打上Authorize標識:
[Authorize] [Route("api/[controller]/[action]")] public class UserController : ControllerBase { }
若是要添加基於角色的受權,可限制操做以下:
[Authorize(Roles = "user")] [Route("api/[controller]/[action]")] public class UserController : ControllerBase { } //多個角色也能夠逗號分隔 [Authorize(Roles = "Administrator,Finance")] [Route("api/[controller]/[action]")] public class UserController : ControllerBase { }
不一樣的角色信息,可經過登陸設置ClaimTypes.Role進行配置;固然,這裏只是簡單的示例說明角色服務的應用,複雜的可經過註冊策略服務,並結合數據庫進行動態配置。
這樣,一個簡單的基於JWT認證受權的工做就完成了。
先後端分離,會涉及到跨域問題,簡單的支持跨域操做以下:
添加擴展支持
public static class CrosExtensions { public static void ConfigureCors(this IServiceCollection services) { services.AddCors(options => options.AddPolicy("CorsPolicy", builder => { builder.AllowAnyMethod() .SetIsOriginAllowed(_ => true) .AllowAnyHeader() .AllowCredentials(); })); //services.AddCors(options => options.AddPolicy("CorsPolicy", //builder => //{ // builder.WithOrigins(new string[] { "http://localhost:13210" }) // .AllowAnyMethod() // .AllowAnyHeader() // .AllowCredentials(); //})); } }
Startup類添加相關注冊以下:
public void ConfigureServices(IServiceCollection services) { services.ConfigureCors(); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseCors("CorsPolicy");//跨域 }
這樣,一個簡單跨域操做就完成了,你也能夠經過設置WithOrigins、WithMethods等方法限制請求地址來源和請求方式。
至此,全篇結束,本篇涉及到的源碼地址:https://github.com/Brooke181/CoreAPI_Demo
下一篇介紹Dapper在.NET Core中的使用,謝謝支持!