如何从onException的方法来发送自定义对象? [英] How to send a custom object from OnException method?
问题描述
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",
});
}
这是我的模型筛选器传递给任何asp.net网站的API。
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
}
我想将对象从这个功能,但这种方法的返回类型为无效
。
我知道的Htt presponseMessage
对象可后仰,但我想这样做定制的方式...
I know HttpResponseMessage
object can be thrown back, but I want to do it customized way...
我该怎么办呢?
推荐答案
我猜你想返回该类作为JSON。
I guess you want to return that class as JSON.
你可以做的仍然是使用的StringContent
的构造函数,但是传递一个JSON序列化的字符串。你可以使用Newtonsoft.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))
});
这篇关于如何从onException的方法来发送自定义对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!