AddControllers/AddMvc方法允許添加自定義ActionFilterAttribute進行過濾
檔案中這么定義Filter:
可以創建自定義篩選器,用于處理橫切關注點, 橫切關注點的示例包括錯誤處理、快取、配置、授權和日志記錄, 篩選器可以避免復制代碼, 例如,錯誤處理例外篩選器可以合并錯誤處理,
通過不同的介面定義,篩選器同時支持同步和異步實作,
同步篩選器在其管道階段之前和之后運行代碼, 例如,OnActionExecuting 在呼叫操作方法之前呼叫, OnActionExecuted 在操作方法回傳之后呼叫,
添加自定義模型驗證
自定義篩選器依賴注入方式
public void ConfigureServices(IServiceCollection services)
{
// Add service filters.
services.AddScoped<AddHeaderResultServiceFilter>();
services.AddScoped<SampleActionFilterAttribute>();
services.AddControllersWithViews(options =>
{
options.Filters.Add(new AddHeaderAttribute("GlobalAddHeader",
"Result filter added to MvcOptions.Filters")); // An instance
options.Filters.Add(typeof(MySampleActionFilter)); // By type
options.Filters.Add(new SampleGlobalActionFilter()); // An instance
})
.ConfigureApiBehaviorOptions(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
}
.net core 中 api 模型驗證
starp.cs
services
.AddControllers(options =>
{
options.Filters.Add(new ModelActionFilter());
options.Filters.AddService<ExceptionFilter>();
options.MaxModelValidationErrors = 50;
options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(
_ => "該欄位不可為空,");
})
.ConfigureApiBehaviorOptions(options =>
{
options.SuppressModelStateInvalidFilter = true;
})
添加ModelActionFilter
public class ModelActionFilter : ActionFilterAttribute, IActionFilter
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var errorResults = new List<ErrorResultDto>();
foreach (var item in context.ModelState)
{
var result = new ErrorResultDto
{
Field = item.Key,
Msg = "",
};
foreach (var error in item.Value.Errors)
{
if (!string.IsNullOrEmpty(result.Msg))
{
result.Msg += '|';
}
result.Msg += error.ErrorMessage;
}
errorResults.Add(result);
}
context.Result = new JsonResult(Result.FromCode(ResultCode.InvalidData, errorResults));
}
}
}
public class ErrorResultDto
{
/// <summary>
/// 引數領域
/// </summary>
public string Field { get; set; }
/// <summary>
/// 錯誤資訊
/// </summary>
public string Msg { get; set; }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/69025.html
標籤:.NET Core
