[英]override OnActionExecuting by HttpActionContext in .NET Core
我有一個帶有 [ValidateModel] 屬性的舊 MVC 程序 web api:
[Route("login")]
[ValidateModel]
public User Login(LoginModel model)
{
}
通過以下代碼驗證模型並返回自定義響應:
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateResponse(
HttpStatusCode.BadRequest,
new CustomErrorResult
{
Succeeded = false,
Errors = actionContext.ModelState.Values.SelectMany(
o => o.Errors.Select(
e => e.ErrorMessage))
});
}
base.OnActionExecuting(actionContext);
}
}
自定義錯誤結果類
public class CustomErrorResult
{
public bool Succeeded { get; set; }
public IEnumerable<string> Errors { get; set; }
}
我現在正在將代碼修改為 .NET Core,如何將此部分修改為 Core 版本?
我研究了很長時間但仍然無法解決這個問題,.NET Core 似乎有一個功能可以抑制啟動/程序文件中的自定義響應?
當使用應用了[ApiController]
屬性的控制器時,ASP.NET Core 通過返回 400 Bad Request 並以ModelState
作為響應正文來自動處理模型驗證錯誤。
參考: 自動 HTTP 400 響應
一種方法是您可以通過以下方式抑制此功能:
services.AddControllers().ConfigureApiBehaviorOptions(options => {
options.SuppressModelStateInvalidFilter = true;
});
並更改您的自定義 ValidateModel:
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(new CustomErrorResult
{
Succeeded = false,
Errors = context.ModelState.Values.SelectMany(
o => o.Errors.Select(
e => e.ErrorMessage))
});
}
base.OnActionExecuting(context);
}
}
另一種不自定義 ValidateModel的方法是在 Startup.cs 中使用自定義響應工廠,如下所示:
services.Configure<ApiBehaviorOptions>(o =>
{
o.InvalidModelStateResponseFactory = actionContext =>
new BadRequestObjectResult(new BadRequestObjectResult(new CustomErrorResult
{
Succeeded = false,
Errors = actionContext.ModelState.Values.SelectMany(
o => o.Errors.Select(
e => e.ErrorMessage))
}));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.