BadRequest自定义错误消息未返回给客户端?

时间:2018-03-18 23:57:15

标签: c# .net asp.net-web-api asp.net-web-api2

我正在使用Web API 2应用,并且我正在实施请求验证。我已经包含了一个如下所示的验证检查:

if (string.IsNullOrEmpty(userCredentials.UserName))
    return BadRequest("UserCredentials.UserName is required");

按预期返回400响应代码,但提供的消息似乎未包含在返回给客户端的响应中。我是否遗漏了实施中的内容,或者是否有一种特殊方式需要处理客户收到的响应?

更新

BadRequest消息返回给Postman但是当我通过控制台应用程序使用C#调用它时,我无法找到验证消息。这是我在控制台应用中使用的代码:

static async Task<User> Authenticate(string domain, string userName, string password)
{
    using (var client = GetHttpClient())
    {
        var encoding = Encoding.GetEncoding("iso-8859-1");
        var userName64 = Convert.ToBase64String(encoding.GetBytes(userName));
        var password64 = Convert.ToBase64String(encoding.GetBytes(password));
        var credentials = new { DomainName = domain, UserName = userName64 /*, Password = password64*/ };
        var response = await client.PostAsJsonAsync("api/v1/auth", credentials);
        var user = await response.Content.ReadAsAsync<User>();
        return user;
        //return response.Content.ReadAsAsync<User>();
    }
}

2 个答案:

答案 0 :(得分:0)

您没有检查错误的回复。您似乎假设所有响应都是200,因为您不检查并尝试将响应内容解析为您的返回类型。

//...

var response = await client.PostAsJsonAsync("api/v1/auth", credentials);
if(response.IsSuccessStatusCode) { // If 200 OK
    //parse response body to desired
    var user = await response.Content.ReadAsAsync<User>();
    return user;
} else {
    //Not 200. You could also consider checking for if status code is 400
    var message = await response.Content.ReadAsStringAsync();
    //Do something with message like
    //throw new Exception(message);
}

//...

答案 1 :(得分:-1)

using(var response = await client.PostAsJsonAsync("api/v1/auth", credentials)){
    if(response.IsSuccessStatusCode) { 
        //This Code is Executed in Case of Success
        var user = await response.Content.ReadAsAsync<User>();
        return user;
    } 
    else {
        //This Code is Executed in Case of In Case of Other Than Success
        var message = await response.Content.ReadAsStringAsync();
    }
}
<块引用>

如果您想在请求错误或 NotFound 等情况下捕获错误消息,您可以使用此重构代码。