我使用ASP.Net Web API和ASP.Net Web API Client nuget包。 当我的客户端调用API并出错时,例如API方法抛出异常, API返回带有InternalServerError状态码和消息的HTTPResponseMessage,但该消息是英文的,我怎样才能获得本消息的本地化版本?ASP.Net Web API失败响应本地化
1
A
回答
0
没有用于本地化这些消息的自动机制,但可以使用HttpResponseMessage.ResponsePhrase自行更改消息。
1
您可以使用HttpResponseMessage类的ReasonPhrase来设置来自Web Api的显式/本地化错误消息。举例来说,目前您的API方法只是抛出一个普遍的例外:
public class CustomerController : ApiController
{
public Customers Get(string id)
{
NorthwindEntities db=new NorthwindEntities();
var data = from item in db.Customers
where item.CustomerID == id
select item;
Customer obj = data.SingleOrDefault();
if (obj == null)
{
throw new Exception("CustomerID Not Found in Database!");
}
else
{
return obj;
}
}
...
}
调用客户端上的API方法与客户的ID是不存在的:
$.ajax({
type: "GET",
url: '/api/Customer',
data: {id:$("#txtCustomerID").val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.CustomerID + " - " + result.CompanyName);
},
error: function (err,type,httpStatus) {
alert(err.status + " - " + err.statusText + " - " + httpStatus);
}
})
将显示相同的500错误你得到
要获得本地化的和有意义的错误消息,您可以使用HttpResponseException类具有本地化的消息ReasonPhrase属性客户端:
public Customer Get(string id)
{
NorthwindEntities db=new NorthwindEntities();
var data = from item in db.Customers
where item.CustomerID == id
select item;
Customer obj = data.SingleOrDefault();
if (obj == null)
{
HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No customer with ID = {0}", id)),
ReasonPhrase = "Localzed message CustomerID Not Found in Database!"
};
throw new HttpResponseException(msg);
}
else
{
return obj;
}
}
相关问题
- 1. asp.net Web API 2 AJAX失败
- 2. ASP.NET MVC 2 - 与jQuery Ajax响应失败
- 3. ASP.NET Web API ReadAsAsync失败,没有错误
- 4. Swift:Main.Storyboard本地化失败
- 5. 设置本地化失败
- 6. c#Web API本地化
- 7. jQuery 2.0 + ASP.NET WebApi POST空响应=失败
- 8. 本地化web api odata最佳实践?
- 9. ASP.NET中的Web API拆分响应
- 10. ASP.NET Web API从响应中删除HttpError
- 11. ASP.NET Core 2.0 Web API响应缓存
- 12. 无法序列化响应主体中的ASP.NET Web API
- 13. 如何使ASP.NET Web API适当地响应403或401?
- 14. ASP.NET WEB API的文本字符串本地化2自主应用程序
- 15. 更改Web API响应格式化
- 16. C#Wcf Web API反序列化响应
- 17. ASP.NET Web API HttpContext响应在IOwinContext响应之前发回
- 18. Web API 2路由失败
- 19. 通过API上传本地CSV失败
- 20. 本地化失败,在Web应用程序中使用强类型资源
- 21. HTTP失败响应覆盖非本地客户端的响应正文
- 22. 维克斯本地化失败的WixIIsExtension,
- 23. MVC可空+本地化失败
- 24. 跨域JSON响应失败
- 25. jQuery UI地图V3 - 本地化响应
- 26. 变化响应头对的ASP.NET Web API的媒体类型格式化
- 27. 从另一本地服务获取响应的Web API请求
- 28. Web API中的API调用失败
- 29. FirebaseApp:Firebase API初始化失败
- 30. Firebase API初始化失败