如何在 IHttpActionResult 返回 BadRequest(Message)

我返回 BadRequest("Failed Invalid Product Id"),返回响应代码 400 和响应正文


{

    "error": {

    "code": "",

    "message": "Failed Invalid Product Id"

     }

}

如何在响应主体中发送响应代码 400,以便获得如下响应主体:


{

    "error": {

    "code": 400,

    "message": "Failed Invalid Product Id"

     }

}


肥皂起泡泡
浏览 114回答 1
1回答

BIG阳

你可以做这样的事情,没有测试它:return Content((HttpStatusCode)400, "Failed Invalid Product Id");如果你真的想有自定义的方式来做到这一点,那么你需要IHttpActionResult用你自己的类来扩展实现,就像下面的例子一样,它是从这个链接中得到启发的:public class ErrorResult : IHttpActionResult{&nbsp; &nbsp; private readonly Error _error;&nbsp; &nbsp; private readonly HttpRequestMessage _request;&nbsp; &nbsp; public ErrorResult(Error error, HttpRequestMessage request)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _error = error;&nbsp; &nbsp; &nbsp; &nbsp; _request = request;&nbsp; &nbsp; }&nbsp; &nbsp; public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var err = new Error()&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Code = _error.Code,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Message = _error.Message&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; var response = new HttpResponseMessage(HttpStatusCode.BadRequest)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Content = new ObjectContent<Error>(err, new JsonMediaTypeFormatter()),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; RequestMessage = _request&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; return Task.FromResult(response);&nbsp; &nbsp; }}public class Error{&nbsp; &nbsp; public string Code { get; set; }&nbsp; &nbsp; public string Message { get; set; }}然后使用它:var err = new Error(){&nbsp; &nbsp; Code = "400",&nbsp; &nbsp; Message = "Failed Invalid Product Id"};return new ErrorResult(err, Request);这将错误返回:
打开App,查看更多内容
随时随地看视频慕课网APP