问题
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