1
public override void OnException(
         System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Exception != null)
            Elmah.ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception);
        base.OnException(actionExecutedContext);


        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            Content = new StringContent(actionExecutedContext.Exception.Message),
            ReasonPhrase = "Deadly Exception",
        });
    }

This is my filter for Model passed to any asp.net web api.

It works like a charm!

But in my case, what I want is to return custom object (strange need) back to user like:

public class ErrorModel
{
   public int StatusCode {get;set;}
   public string ErrorMsg {get;set;}
}

What I want to do is (if it is possible):

 public override void OnException(
         System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
    {



        ErrorModel er = new ErrorModel(); //////////// object of class


        if (actionExecutedContext.Exception != null)

         er.StatusCode =200
         er.ErrorMsg="My Custom Msg" 

        // return er object 

    }

I want to send the object back from this function but the return type of this method is void.

I know HttpResponseMessage object can be thrown back, but I want to do it customized way...

How can I do it?

1 Answer 1

2

I guess you want to return that class as JSON.

What you could do is still use the StringContent constructor, but pass in a JSON serialized string. You could use Newtonsoft.Json as serialized.

throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
    Content = new StringContent(JsonConvert.SerializeObject(yourObject))
});
Sign up to request clarification or add additional context in comments.

3 Comments

Done upvoting... If you could help me for next question mentioned in above link...
Thanks. I am not sure what the answer is. I will take a look.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.