我有這個驗證過濾器類。
public class ValidationFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.ModelState.IsValid)
{
var errorsInModelState = context.ModelState
.Where(x => x.Value?.Errors.Count > 0)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value?.Errors.Select(x => x.ErrorMessage)).ToArray();
var errorResponse = new ErrorResponse();
foreach (var error in errorsInModelState)
{
foreach (var subError in error.Value)
{
var errorModel = new Error
{
FieldName = error.Key,
Message = subError
};
errorResponse.Errors.Add(errorModel);
}
}
context.Result = new BadRequestObjectResult(errorResponse);
return;
}
await next();
}
}
在 ASP.NET 5 中,我們添加如下所示的 ValidationFilter
services
.AddMvc(options =>
{
options.EnableEndpointRouting = false;
options.Filters.Add<ValidationFilter>();
})
.AddFluentValidation(mvcConfiguration => mvcConfiguration.RegisterValidatorsFromAssemblyContaining<Startup>())
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
如何Program.cs在 .NET 6 中添加它?
uj5u.com熱心網友回復:
在 .Net6 中,我們使用builder.Services.AddControllersWithViews()而不是services.AddMvc(). 所以你可以這樣設定:
builder.Services.AddControllersWithViews(options =>
{
options.Filters.Add<ValidationFilter>();
});
更多關于.NET 6新配置可以參考這個鏈接。
uj5u.com熱心網友回復:
您可以定義一個繼承自該類的類,該類ActionFilterAttribute
根據以下示例代碼向回應添加標頭:
public class ResponseHeaderAttribute : ActionFilterAttribute
{
private readonly string _name;
private readonly string _value;
public ResponseHeaderAttribute(string name, string value) =>
(_name, _value) = (name, value);
public override void OnResultExecuting(ResultExecutingContext context)
{
context.HttpContext.Response.Headers.Add(_name, _value);
base.OnResultExecuting(context);
}
}
然后您可以在 Program.cs 檔案中添加過濾器(基于 dot net 6 新控制臺模板):
builder.Services.AddControllersWithViews(options =>
{
options.Filters.Add<ResponseHeaderAttribute>();
});
現在您可以在控制器中使用它,例如:
[ResponseHeader("my-filter", "which has the value")]
public IActionResult DoSomething() =>
Content("I'm trying to do something");
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/475669.html
上一篇:Docker錯誤:dotnet-file.dll不存在
下一篇:ASP.NETCore-EntityFrameworkCore-下拉串列-DbContextSaveChanges問題
