在ASP.NET 1.0的核心API网页错误处理(发送ex.Message到客户端) [英] Error handling in ASP.NET Core 1.0 Web API (Sending ex.Message to the client)
问题描述
我有一个ASP.NET 1.0的核心网络API应用程序,并试图找出如何通过异常消息给客户端,如果我的控制器调用了错误的函数。
I have an ASP.NET Core 1.0 Web API application and trying to figure out how to pass the exception message to the client if a function that my controller is calling errors out.
我已经尝试了这么多东西,但没有实现IActionResult。
I have tried so many things, but nothing implements IActionResult.
我不明白为什么这不是一个普通的东西,人们需要。如果没有如实无解有人可以告诉我为什么?
I don't understand why this isn't a common thing that people need. If there truthfully is no solution can someone tell me why?
我看到一些文件有使用的Htt presponseException(HTT presponseMessage),但为了使用这个我必须安装compat的垫片。是否有核心1.0做这些事情的新方式?
I do see some documentation out there using HttpResponseException(HttpResponseMessage), but in order to use this I have to install the compat shim. Is there a new way of doing these things in Core 1.0?
下面是我一直在试图用垫片,但它不工作:
Here is something I have been trying with the shim but it isn't working:
// GET: api/customers/{id}
[HttpGet("{id}", Name = "GetCustomer")]
public IActionResult GetById(int id)
{
Customer c = _customersService.GetCustomerById(id);
if (c == null)
{
var response = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent("Customer doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
StatusCode = HttpStatusCode.NotFound
};
throw new HttpResponseException(response);
//return NotFound();
}
return new ObjectResult(c);
}
在该型Htt presponseException被抛出,我期待在客户端上并不能找到我的内容发送任何信息。
When the HttpResponseException is thrown, I look on the client and can't find the message I am sending anything in the content.
推荐答案
下面是一个简单的错误DTO类
Here is an simple error DTO class
public class ErrorDto
{
public int Code {get;set;}
public string Message { get; set; }
// other fields
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
然后使用的ExceptionHandler 中间件:
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = 500; // or another Status accordingly to Exception Type
context.Response.ContentType = "application/json";
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
var ex = error.Error;
await context.Response.WriteAsync(new ErrorDto()
{
Code = <your custom code based on Exception Type>,
Message = ex.Message // or your custom message
// other custom data
}.ToString(), Encoding.UTF8);
}
});
});
这篇关于在ASP.NET 1.0的核心API网页错误处理(发送ex.Message到客户端)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!