我正在使用HttpClient来调用此Web API
using (var client = new HttpClient(new HttpClientHandler() { Credentials = _credentials }))
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return await client.PostAsJsonAsync(controlActionPath, entityObject);
}
Web API控制器我正在抛出以下错误:
throw new DuplicateNameException("User already exists.");
但是,网络应用始终会收到内部服务器错误,而不是DuplicateNameException
。
如果有人建议从Web API将确切的异常恢复回Web应用程序的最佳方法,那将会很有帮助。
答案 0 :(得分:3)
因为您抛出异常,它会自动成为内部服务器错误,因为它仍然在您的内部服务器端代码中。您可以像this answer中那样创建异常处理程序,也可以按照Web API documentation on exception handling中的详细说明抛出特定的HttpResponseException
类型:
var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
ReasonPhrase = "User already exists."
};
throw new HttpResponseException(response);