我使用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初始化失敗