我有一个ASP.NET Core1.0WebAPI应用程序,并试图弄清楚如果我的控制器正在调用的函数出错,如何将异常消息传递给客户端。
我尝试了很多方法,但都没有实现IActionResult
。
我不明白为什么这不是人们需要的普通东西。如果真的没有解决方案,谁能告诉我为什么?
我确实看到一些使用HttpResponseException(HttpResponseMessage)
的文档,但是为了使用它,我必须安装compat shim。在Core1.0中有没有一种新的方式来做这些事情?
下面是我一直在尝试的填充程序,但它不起作用:
// 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);
}
当抛出HttpResponseException
时,我查看客户端,但找不到要在内容中发送任何内容的消息。
发布于 2016-06-24 21:55:23
下面是一个简单的错误DTO类
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);
}
});
});
发布于 2016-08-21 04:47:44
是的,可以将状态代码更改为您需要的任何代码:
在CustomExceptionFilterAttribute.cs文件中,按如下所示修改代码:
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
var exception = context.Exception;
context.Result = new ContentResult
{
Content = $"Error: {exception.Message}",
ContentType = "text/plain",
// change to whatever status code you want to send out
StatusCode = (int?)HttpStatusCode.BadRequest
};
}
}
差不多就是这样。
如果您有自定义的异常,那么您也可以在从上下文中抓取抛出的异常时检查它们。接下来,您可以根据代码中发生的情况发送不同的HTTP状态代码。
希望这能有所帮助。
发布于 2016-06-24 21:44:59
您可以创建自定义异常过滤器,如下所示
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
var exception = context.Exception;
context.Result = new JsonResult(exception.Message);
}
}
然后将上述属性应用于您的控制器。
[Route("api/[controller]")]
[CustomExceptionFilter]
public class ValuesController : Controller
{
// GET: api/values
[HttpGet]
public IEnumerable<string> Get()
{
throw new Exception("Suckers");
return new string[] { "value1", "value2" };
}
}
https://stackoverflow.com/questions/38014379
复制相似问题