This project is read-only.

Response localization in Web API

Topics: ASP.NET Web API
Nov 8, 2013 at 10:19 AM
Edited Nov 8, 2013 at 12:59 PM

We would like to know if it is possible to handle and/or localize all aumatic messages returned by our Web API.

Our client application support several languages depending on user profile, so all our custom menssages are returned according to each user culture.

There are some cases where Web API framework returns error messages just in english language.

For example:

1. When we validate our model objects as follows:
    public class ValidateModelAttribute : ActionFilterAttribute
        public override void OnActionExecuting(HttpActionContext actionContext)
            // Validate model (custom validation)
            // ...

            // Check if modelstate is valid
            if (!actionContext.ModelState.IsValid)
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, actionContext.ModelState);
Internal ModelState exceptions messages, where model property types are validated automatically (not by our custom validation process), are shown always in this way:
{"Message":"The request is invalid.","ModelState":{"product.ProductId":["Error converting value {null} to type 'System.Int32'. Path 'ProductId', line 1, position 44."],"product.Price":["Error converting value \"\" to type 'System.Double'. Path 'Price', line 1, position 103."],"product.Discount":["Error converting value \"\" to type 'System.Double'. Path 'Discount', line 1, position 117."]}}
Or when only custom messages are added in ModelState, a mix of culture messages is being send to client:
{"Message":"The request is invalid.","ModelState":{"ProductName":["S'han especificat valors erronis."]}}
_ _

2. This same problem, regarding handling and localization of default response messages, is reproduced also when an invalid route is called:

For example, with an invalid url, we receive this english response:
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/api/invalid_route/3'.","MessageDetail":"No type was found that matches the controller named 'perfil'."}
_ _

3. Another example of this situation is when an Authorization is required:

If we call a controller method with an [Authorize] attribute, we get this invariant message:
{"Message":"Authorization has been denied for this request."}
_ _

Is there any way to localize all this kind of messages?

Nov 18, 2013 at 10:08 AM
Edited Nov 18, 2013 at 10:08 AM

Any suggestion or workaround about this issue?

May be implementing an HttpMessageHandler and processing the response?

Any idea about other simpler way?