How to send a custom object from OnException method?

寵の児 提交于 2020-01-15 15:31:32

问题


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:


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


来源:https://stackoverflow.com/questions/30622261/how-to-send-a-custom-object-from-onexception-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!