相关疑难解决方法(0)

在到达ASP.NET Core中的控制器之前拦截错误请求

如果收到的请求是BadRequest,我有一个逻辑可以应用,为此我创建了一个过滤器:

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            // Apply logic
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在启动中:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options => { options.Filters.Add<ValidateModelAttribute>(); });
}
Run Code Online (Sandbox Code Playgroud)

控制器:

[Route("api/[controller]")]
[ApiController]
public class VerifyController : ControllerBase
{
    [Route("test")]
    [HttpPost]
    [ValidateModel]
    public ActionResult<Guid> validationTest(PersonalInfo personalInfo)
    {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

模型:

public class PersonalInfo
{
    public string FirstName { get; set; }
    [RegularExpression("\\d{4}-?\\d{2}-?\\d{2}", ErrorMessage = "Date must be properly formatted according to ISO 8601")]
    public …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core-mvc asp.net-core

4
推荐指数
1
解决办法
2489
查看次数

标签 统计

asp.net-core ×1

asp.net-core-mvc ×1

c# ×1