我正在 WebAPI 2 中处理一项服务,端点当前返回一个 IHttpActionResult
。我想返回状态代码 422
,但由于它不在 HttpStatusCode
枚举中,我不知道如何发送它,因为所有的构造函数需要 HttpStatusCode
就目前而言,我正在返回 BadResult(message)
,但返回 422
+ 消息对我的客户来说更具描述性和有用性。有什么想法吗?
最佳答案
根据 C# 规范:
The set of values that an enum type can take on is not limited by its enum members. In particular, any value of the underlying type of an enum can be cast to the enum type and is a distinct valid value of that enum type
因此您可以将状态码 422 转换为 HttpStatusCode。
示例 Controller :
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace CompanyName.Controllers.Api
{
[RoutePrefix("services/noop")]
[AllowAnonymous]
public class NoOpController : ApiController
{
[Route]
[HttpGet]
public IHttpActionResult GetNoop()
{
return new System.Web.Http.Results.ResponseMessageResult(
Request.CreateErrorResponse(
(HttpStatusCode)422,
new HttpError("Something goes wrong")
)
);
}
}
}
关于c# - 从 WebAPI 2 端点返回自定义 HTTP 状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23399272/