【问题标题】:How I can adjust which fields I will have in the response of a model validation (.NET Core Web Api)?如何调整模型验证(.NET Core Web Api)响应中的字段?
【发布时间】:2020-10-24 11:21:01
【问题描述】:

我有以下回应:

{
  "errors": {
    "name": [
      "The Name field is required."
    ]
  },
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "|df89b6cf-4d6da62fe5671a5c."
}

其实我不需要typetitletraceId

我在Startup.cs中没有任何额外的配置:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseNpgsql(Configuration.GetConnectionString("MainConnectionString")));
    
    services.AddAuthenticationWithBearer(Configuration);

    services.AddControllers().AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ContractResolver = new DefaultContractResolver
        {
            NamingStrategy = new CamelCaseNamingStrategy
            {
                ProcessDictionaryKeys = true,
                OverrideSpecifiedNames = true,
                ProcessExtensionDataNames = true
            },
        };
    });
        
    services.AddSwaggerConfiguration();
}

我有非常简单的模型:

public class UpdateProfileRequest
{
    [Required]
    [StringLength(20)]
    public string Name { get; set; }
    [Required]
    [StringLength(20)]
    public string About { get; set; }
    public int Age { get; set; }
    public string JobInfo { get; set; }
    public string HobbyInfo { get; set; }
    public string Email { get; set; }
}

这是控制器的动作:

[Authorize]
[HttpPost("[action]")]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public IActionResult UpdateProfile(UpdateProfileRequest request)
{
    
    return Ok(new {UserName = "test"});
}

所以,问题。如何为每个响应删除字段:typetitletraceId。 有这么简单的方法吗?

【问题讨论】:

    标签: c# .net .net-core asp.net-core-webapi


    【解决方案1】:

    好的,我已经用最优雅的方式解决了它。为此,我不得不对框架的内部机制进行一些研究。

    1. 我在静态类中创建了以下方法,方法如下:
            public static IActionResult MakeValidationResponse(ActionContext context)
            {
                var problemDetails = new ValidationProblemDetails(context.ModelState)
                {
                    Status = StatusCodes.Status400BadRequest,
                };
                // My app calls Chat, so, that's why I called this var as chatProblemDetails
                var chatProblemDetails = new ChatProblemDetails
                {
                    Status = problemDetails.Status,
                    Errors = problemDetails.Errors,
                };
                
                var result = new BadRequestObjectResult(chatProblemDetails);
    
                result.ContentTypes.Add("application/problem+json");
    
                return result;
            }
        }
    
    
    1. 为响应创建了 DTO 类:
        public class ChatProblemDetails
        {
            public int? Status { get; set; }
            public IDictionary<string, string[]> Errors { get; set; }
        }
    
    1. 最后,在Startup.cs类上添加如下配置:
    services.AddControllers().ConfigureApiBehaviorOptions(options =>
        {
            options.InvalidModelStateResponseFactory = InvalidModelStateResponse.MakeValidationResponse;
        }). ... 
    

    还有利润!现在验证响应如下所示:

    {
      "status": 400,
      "errors": {
        "name": [
          "The Name field is required."
        ]
      }
    }
    

    没有traceId,没有type,没有多余的噪音!感谢您的阅读!

    【讨论】:

    • 内容类型application/problem+json 表示RFC 7807。如果您不想使用 RFC 7807 - 您应该使用默认内容类型。
    猜你喜欢
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 2023-03-23
    • 2017-02-23
    • 1970-01-01
    • 2018-08-24
    相关资源
    最近更新 更多