从Netcore 2.2 Web API的响应中获取ErrorMessage [英] Get ErrorMessage from Response in Netcore 2.2 Web API

查看:274
本文介绍了从Netcore 2.2 Web API的响应中获取ErrorMessage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用空的用户名和密码调用Register方法.所以我收到了这个结果:

I call Register method with empty username and password. So I received this result:

{
    "errors": {
        "Password": [
            "The Password field is required.",
            "Password length is between 4 and 8."
        ],
        "Username": [
            "The Username field is required."
        ]
    },
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "0HLJIO56EGJEV:00000001"
}

我的Dto:

public class UserForRegisterDto
{
    [Required]
    public string Username { get; set; }
    [Required]
    [StringLength(8, MinimumLength = 4, ErrorMessage = "Password length is between 4 and 8.")]
    public string Password { get; set; }
}

我只想从响应中获取错误属性,该怎么办?

I only want to get errors attribute from response, What should I do?

推荐答案

这是

返回客户端错误状态代码(4xx)的IActionResult现在返回ProblemDetails正文.

The docs describe that this can be disabled when calling AddMvc inside of ConfigureServices, like this:

services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressUseValidationProblemDetailsForInvalidModelStateResponses = true;
    });

这将导致2.2之前的行为,该行为只会序列化错误.

This will result in the pre-2.2 behavior, which will serialise only the errors.

这篇关于从Netcore 2.2 Web API的响应中获取ErrorMessage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆