user1826289
user1826289

Reputation:

ASP.Net Web API failure response localization

I use ASP.Net Web API and ASP.Net Web API Client nuget packages. When my client calls API and something goes wrong, for example API method thrown an exception, the API returns HTTPResponseMessage with InternalServerError status code and message, but the message is in English, how can I get localized version of this message?

Upvotes: 2

Views: 1345

Answers (2)

chridam
chridam

Reputation: 103375

You can use the ReasonPhrase of the HttpResponseMessage class to set explicit/localized error messages from the Web Api. For instance, currently your API method is just throwing a general exception:

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;
        }
    }
    ...
}

Invoking the API method on client side with a customer ID that is non-existant:

$.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);
  }
})

will display the same 500 error you are getting 500 Error Message

To get a localized and meaningful error messages to the client you can use the HttpResponseException class with the ReasonPhrase property having the localized message:

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;
    }
}

Upvotes: 1

Darrel Miller
Darrel Miller

Reputation: 142094

There is no automatic mechanism for localizing these messages but you can use HttpResponseMessage.ResponsePhrase to change the message yourself.

Upvotes: 1

Related Questions