我正在使用WEBAPI 2我的后端是我的App.I我在一些好博客的帮助下使用自定义异常处理,现在我正在使用它的工作好,但我需要显示我传递的自定义消息我的自定义异常需要帮助,下面是我的代码!
public class GlobalException: System.Web.Http.ExceptionHandling.ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
if (context.Exception is ArgumentNullException)
{
var result = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
//Here i am getting some different value in message and in ParamName its give my custom message,How to access the ParamName rather then context.Exception.Message
Content = new StringContent(context.Exception.Message),
ReasonPhrase = "ArgumentNullException"
};
context.Result = new ArgumentNullResult(context.Request, result);
}
else
{
}
}
public class ArgumentNullResult : IHttpActionResult
{
private HttpRequestMessage _request;
private HttpResponseMessage _httpResponseMessage;
public ArgumentNullResult(HttpRequestMessage request, HttpResponseMessage httpResponseMessage)
{
_request = request;
_httpResponseMessage = httpResponseMessage;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(_httpResponseMessage);
}
}
}
//Controller Method in WEBAPI//
public IHttpActionResult Sendmessage()
{
//here i am send null value with my custom message
throw new ArgumentNullException("Test Null Value");
}
答案 0 :(得分:0)
为了将“Test Null Value”作为内容而不是“Value not not null。参数名称:Test Value Cant为null”,如果需要具有不同的行为,则应使用常用的Exception或自定义异常。
您不能使用期望参数名称的ArgumentNullException并相应地格式化消息