c# - 从 WebAPI 2 端点返回自定义 HTTP 状态代码

标签 c# asp.net-web-api http-status-code-404

我正在 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/

相关文章:

c# - Servicestack 期望较低的程序集版本

c# - 以编程方式将pdf转换为word

c# - 从 C# 在 Quickbooks Online 中创建客户

C# WebApi 传入客户端证书始终为空

java - 在 Tomcat Web 应用程序中重新加载页面时出现 404 错误

rest - 对于未找到的资源集合,最合适的 HTTP 状态是什么?

c# - 查找系统和程序内存使用情况的替代方法

c# - 将 JObject 转换为匿名对象

c# - ASP.NET Identity 验证 ResetPassword token 是否已过期

php - 使用 nginx 和 fastcgi 捕获 PHP 404 错误