我有以下Web API 2.0调用:
[System.Web.Http.Route("api/createuser")]
[System.Web.Http.HttpPost]
public async Task<IHttpActionResult> CreateUser([FromBody] WDUser value)
{
var user = value;
if (string.IsNullOrEmpty(user.Email))
{
throw new ProcessException($"Email is blank.");
}
return Ok("all good");
}
ProcessException很简单:
internal class ProcessException : Exception
{
public ProcessException()
{
}
public ProcessException(string message) : base(message)
{
}
}
我这样称呼我的api:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:49352/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var departmentPost = new WDUser() { Email= "" };
HttpResponseMessage responsePost = client.PostAsJsonAsync("api/createuser", departmentPost).Result;
if (responsePost.IsSuccessStatusCode)
{
// Get the URI of the created resource.
Uri returnUrl = responsePost.Headers.Location;
Console.WriteLine(returnUrl);
}
}
如果我提供电子邮件,则API会返回正常状态。如您所见,我故意将电子邮件留空。我进行API调用并返回错误,但我找不到消息&#34;电子邮件是空白&#34;
如何检索从API返回的错误消息?
答案 0 :(得分:1)
试试这个:
if (responsePost.IsSuccessStatusCode)
{
// Get the URI of the created resource.
Uri returnUrl = responsePost.Headers.Location;
Console.WriteLine(returnUrl);
}
else
{
string content = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(content);
}