在RC1中,我会这样做:
[HttpPost]
public IActionResult Post([FromBody]string something)
{
try{
// ...
}
catch(Exception e)
{
return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError);
}
}
在RC2中,不再有HttpStatusCodeResult,也没有什么我可以找到,让我返回一个500类型的IActionResult。
现在的方法与我要求的完全不同吗?我们在控制器代码中不再尝试捕获了吗?我们只是让框架向API调用者抛出一个通用的500异常吗?对于开发,我如何才能看到确切的异常堆栈?
Microsoft.AspNetCore.Mvc的内置Problem()方法将返回一个基于RFC 7807的“问题细节”响应。NET Core 3.0及更高版本)。只要没有显式地设置其他状态,它将始终返回状态代码500。
[HttpPost]
public IActionResult Post([FromBody] string value)
{
try
{
// ...
}
catch (Exception ex)
{
return Problem(
//all parameters are optional:
//detail: "Error while processing posted data."; //an explanation, ex.Stacktrace, ...
//instance: "/city/London" //A reference that identifies the specific occurrence of the problem
//title: "An error occured." //a short title, maybe ex.Message
//statusCode: StatusCodes.Status504GatewayTimeout, //will always return code 500 if not explicitly set
//type: "http://example.com/errors/error-123-details" //a reference to more information
);
}
}
如果不设置任何参数,它将返回:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.6.1",
"title": "An error occured while processing your request.",
"status": 500,
"traceId": "|fadaed95-4d06eb16160e4996."
}
有关“问题详细信息”参数的更多信息:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.problemdetails?view=aspnetcore-5.0
Microsoft.AspNetCore.Mvc的内置Problem()方法将返回一个基于RFC 7807的“问题细节”响应。NET Core 3.0及更高版本)。只要没有显式地设置其他状态,它将始终返回状态代码500。
[HttpPost]
public IActionResult Post([FromBody] string value)
{
try
{
// ...
}
catch (Exception ex)
{
return Problem(
//all parameters are optional:
//detail: "Error while processing posted data."; //an explanation, ex.Stacktrace, ...
//instance: "/city/London" //A reference that identifies the specific occurrence of the problem
//title: "An error occured." //a short title, maybe ex.Message
//statusCode: StatusCodes.Status504GatewayTimeout, //will always return code 500 if not explicitly set
//type: "http://example.com/errors/error-123-details" //a reference to more information
);
}
}
如果不设置任何参数,它将返回:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.6.1",
"title": "An error occured while processing your request.",
"status": 500,
"traceId": "|fadaed95-4d06eb16160e4996."
}
有关“问题详细信息”参数的更多信息:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.problemdetails?view=aspnetcore-5.0
对于API响应(使用net core),我已经尝试过了,似乎工作得很好:
var err = Content(JsonConvert.SerializeObject(response, SerializerSettings), "application/x-javascript", contentEncoding: System.Text.Encoding.UTF8);
err.StatusCode = StatusCodes.Status500InternalServerError;
return err;
您只需要首先创建一个响应对象,然后响应这个。这样做,我们可以保留内容类型、编码,并添加状态代码。
只是添加这个供将来参考,谁是卡在以及想要一个快速和简单的方法来做到这一点。