c# - ASP.NET 核心 : Custom validation

标签 c# asp.net asp.net-core asp.net-core-2.1

背景

我有一个用 asp.net core v2.1 编写的 web api。这是我的服务公开的功能:

[HttpPost]
[Route("submit")]
public async Task<ActionResult<int>> DoIt(CustomModel model)
{
    if (!ModelState.IsValid)
        return new StatusCodeResult(403); // Custom 403 will be here.

    // ...
}

这是CustomModel:

public class CustomModel
{
    [Required]
    public int MagicNumber { get; set; }
}

在客户端不向服务器提供 MagicNumber 之前,这种组合(方法+模型)工作正常。

问题

与旧的 asp.net(.net 框架)相比,当模型验证失败时 - 将自动向客户端发送 403 错误消息。

我想阻止这种默认行为并向用户提供自定义错误消息。我更喜欢这样定义自定义响应:

[HttpPost]
[Route("submit")]
public async Task<ActionResult<int>> Submit(CustomModel model)
{
    if (!ModelState.IsValid)
        return new CustomErrorCode_BadRequest();
    //...
}

我尝试过的事情

我可以防止自动“错误请求”响应的唯一方法是将此代码添加到 Startup.cs 文件

services.AddMvc(options => options.ModelValidatorProviders.Clear());

添加这行代码后,我可以访问我的 if (!ModelState.IsValid) 语句。在此之前,该请求在较早的步骤中被阻止。不幸的是,ModelState.IsValid 总是返回 true(无论输入是什么)。我猜这是因为我“清除”了所有验证器——这听起来是个坏主意。

应该怎么做?

谢谢!

最佳答案

感谢@Compufreak(来源:https://stackoverflow.com/a/51522487/3085985)将此代码添加到 Starup.cs 解决了问题:

    services.Configure<ApiBehaviorOptions>(opt =>
    {
        opt.SuppressModelStateInvalidFilter = true;
    });

关于c# - ASP.NET 核心 : Custom validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52421451/

相关文章:

c# - System.Security.Cryptography.HMACSHA1 存在于具有相同命名空间的两个程序集中

c# - Caliburn - ShellFramework - Show.MessageBox

c# - 按字符串排序列表以查找较新版本 C#

c# - 在.NET中使用Win32 API模拟按钮点击

c# - Aspose.Cells.CellsException - "You are using an evaluation copy and have opened files exceeding limitation"

asp.net-core - 从 ApplicationService 基类返回一个文件

asp.net-core - Microsoft Distributed Redis Cache - 根据模式获取键

c# - 将 ASP.NET Core 5.0 部署到 Ubuntu 20.04,出现 500 服务器错误和白屏

asp.net - 为什么我的 cookie 设置没有被应用?

c# - 验证以确保时差在 2 小时以内