Sachin Kumar
Sachin Kumar

Reputation: 996

MVC WebApi. Want to get format of HttpResponseMessage according to current formatter

Below is my Get method of MVC Web Api RC.

public Employee Get(int id)
{
     Employee emp= null;

     //try getting the Employee with given id, if not found, gracefully return error message with notfound status
     if (!_repository.TryGet(id, out emp))
         throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound)
         {
             Content = new StringContent("Sorry! no Employee found with id " + id),
             ReasonPhrase = "Error"
         });

      return emp;
}

Here problem is that whenever an error is thrown "Sorry! no Employee found with id ", is just in a plane text format. However i wanted to set the format as per my current formatter. Like by default i have set XML formatter in my global.asax. So the error should be displayed in XML format. Something like :

<error>
  <error>Sorry! no Employee found with id </error>
</error>

similarly for Json formatter. It should be :

[{"errror","Sorry! no Employee found with id"}]

Thanks in advance

Upvotes: 2

Views: 1652

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039538

You are returning a StringContent. This means that the contents will be returned as-is and it is up to you to format it.

Personally I would define a model:

public class Error
{
    public string Message { get; set; }
}

and then:

if (!_repository.TryGet(id, out emp))
{
    var response = Request.CreateResponse(
        HttpStatusCode.NotFound,
        new Error { Message = "Sorry! no Employee found with id " + id }
    );
    throw new HttpResponseException(response);
}

A XML Accept enabled client would then see:

<Error xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/AppName.Models">
    <Message>Sorry! no Employee found with id 78</Message>
</Error>

and a JSON Accept enabled client would see:

{"Message":"Sorry! no Employee found with id 78"}

Upvotes: 7

Related Questions