c#-从Web API 2端点返回自定义HTTP状态代码
我正在使用WebAPI 2中的服务,并且端点当前返回IHttpActionResult。我想返回状态码BadResult(message),但是由于它不在422枚举中,所以我不知所措 发送,因为所有构造函数都需要一个HttpStatusCode参数
就目前情况而言,我将返回BadResult(message),但是返回422 +消息对我的客户来说更具描述性和实用性。 有任何想法吗?
5个解决方案
78 votes
根据C#规范:
枚举类型可以采用的一组值不受其枚举成员的限制。 特别是,枚举的基础类型的任何值都可以转换为枚举类型,并且是该枚举类型的不同有效值
因此,您可以将状态代码422强制转换为HttpStatusCode。
控制器示例:
using ;
using .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")
)
);
}
}
}
lilo.jacob answered -02-29T15:05:06Z
23 votes
return Content((HttpStatusCode) 422, whatEver);
功劳是:对于非OK响应,返回带有IHttpActionResult的内容
并且您的代码必须为<= 999
请忽略100到200之间的代码。
peyman answered -02-29T15:05:34Z
3 votes
我用这种方式简单而优雅。
public ActionResult Validate(User user)
{
return new HttpStatusCodeResult((HttpStatusCode)500,
"My custom internal server error.");
}
然后是角度控制器。
function errorCallBack(response) {
$scope.response = {
code: response.status,
text: response.statusText
}});
希望对您有帮助。
Ricardo G Saraiva answered -02-29T15:06:03Z
0 votes
为此,您可能需要使用操作过滤器属性。 没有什么花哨。 只需创建一个类并从c#中的ActionFilterAttribute类继承即可。 然后重写名为OnActionExecuting的方法以实现此方法。 然后,只需在任何控制器的头上使用此过滤器即可。 以下是一个演示。
在需要在ActionFilterAttribute中生成基于自定义状态代码的消息的情况下,可以通过以下方式编写:
if (necessity_to_send_custom_code)
{
actionContext.Response = actionContext.Request.CreateResponse((HttpStatusCode)855, "This is custom error message for you");
}
希望这可以帮助。
Sajeeb Chandan answered -02-29T15:06:32Z
0 votes
另一个简化的示例:
public class MyController : ApiController
{
public IHttpActionResult Get()
{
HttpStatusCode codeNotDefined = (HttpStatusCode)422;
return Content(codeNotDefined, "message to be sent in response body");
}
}
Content是在抽象类ApiController(控制器的基础)中定义的虚拟方法。 参见以下声明:
protected internal virtual NegotiatedContentResult Content(HttpStatusCode statusCode, T value);
themefield answered -02-29T15:06:59Z