1.若是Content-Type是application/json,而POST和PUT的參數是[FromBody] string value,那麼若是curl -d的值是'{"Name": "uuu"}'這種JSON字符串將會報錯(暫不知爲什麼),可是若是-d的值是'aas'這種普通字符串則不會有問題;json
可是若是將上面的string value改爲AClass value,而後AClass裏有個Name的屬性那麼-d '{"Name": "uuu"}'也是不會有問題的(這是由於字符串'sss'自己就是對於string類型對象,就像33對於類型是int同樣[FromBody] int value);緩存
2.默認狀況下WebApi對json請求體的屬性名大小寫不敏感,上訴的Name寫成name也同樣,哪怕AClass的屬性是叫Name而非name;app
3.WebApi裏的IActionFilter的實現類就相似SpringMVC裏的只有before和after的Aspect,它可以對參數進行一個修改,可以記錄日誌,可是不能像Interceptor同樣進行一個邏輯判斷髮現不合要求就中止請求;curl
在IActionFilter裏已經將Request.Body轉換爲了[FromBody]的參數的值,而因爲Request.Body也是和Java同樣只能被讀取一次的,所以在IActionFilter裏開啓filterContext.HttpContext.Request.EnableBuffering();是無效的,流已經被讀取完了;async
IActionFilter對象的添加方式是經過ide
services.AddMvc(opt => { // 添加過濾器 opt.Filters.Add(typeof(ValidatorActionFilter)); })
4.能夠不實現IActionFilter而是直接繼承ActionFilterAttribute(ActionFilterAttribute同時兼具IActionFilter和IResultFilter,可是IExceptionFilter貌似沒有對應的Attribute),這個類相似一個適配器,並且同時具備特性這個功能;url
5.對於.net core2.2以上的WebApi的攔截器若是要實現不符合要求就pass掉能夠用以下方法.net
public class AuthFilter : ActionFilterAttribute { public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { if (!(context.ActionDescriptor is ControllerActionDescriptor)) { throw new ArgumentException(); } Console.WriteLine("開始啦啦啦啦啦" + "###" + ((ControllerActionDescriptor) context.ActionDescriptor).MethodInfo.CustomAttributes.Aggregate("", (a, b) => string.Join(",", a, b.AttributeType))); if (context.ActionDescriptor.DisplayName.Contains("Get")) { context.HttpContext.Response.Headers.Add("Content-Type", "application/json;charset=utf8"); await context.HttpContext.Response.WriteAsync("鑑權失敗", Encoding.UTF8); } else {
// 只有Async的才能實現Around的功能 var resultContext = await next(); } Console.WriteLine("結束啦啦啦啦啦"); } }
6.能夠在Startup裏經過app來Use一箇中間件,這個中間件就相似Tomcat的Filter:日誌
app.UseHttpsRedirection(); app.Use(BarMiddleware); app.UseMvc(); } private static RequestDelegate BarMiddleware(RequestDelegate next) => async context => { Console.WriteLine("比IActionFilter最早的要先"); context.Request.EnableBuffering(); await next(context); Console.WriteLine("比IActionFilter最後的要後"); };
7..net core2.2裏的WebApi的HttpContext.Request.Body的流自己就是可重複讀取的,不須要再用HttpContext.Request.EnableBuffering();開啓請求體緩存,不過主動讀取Body以前要:HttpContext.Request.Body.Position = 0;而後用StreamReader來讀取。中間件