2013-11-15 47 views
1

我使用ASP.Net Web API和ASP.Net Web API Client nuget包。 當我的客戶端調用API並出錯時,例如API方法拋出異常, API返回帶有InternalServerError狀態碼和消息的HTTPResponseMessage,但該消息是英文的,我怎樣才能獲得本消息的本地化版本?ASP.Net Web API失敗響應本地化

回答

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錯誤你得到 500 Error Message

要獲得本地化的和有意義的錯誤消息,您可以使用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; 
    } 
}