2

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

1 Answer 1

7

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"}
Sign up to request clarification or add additional context in comments.

3 Comments

What do you mean by stuck? What's the problem?
Sorry, i had pressed enter key, that posted my incomplete message. Actually i wanted to ask that i am stuck at OnActionExecuting event of a filter (ActionFilterAttribute). public override void OnActionExecuting(HttpActionContext context) { context.Response = ? (how to send out error messsge from here, in the same way we did it from Get method)}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.