1 回答

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
你可以做這樣的事情,沒有測(cè)試它:
return Content((HttpStatusCode)400, "Failed Invalid Product Id");
如果你真的想有自定義的方式來做到這一點(diǎn),那么你需要IHttpActionResult用你自己的類來擴(kuò)展實(shí)現(xiàn),就像下面的例子一樣,它是從這個(gè)鏈接中得到啟發(fā)的:
public class ErrorResult : IHttpActionResult
{
private readonly Error _error;
private readonly HttpRequestMessage _request;
public ErrorResult(Error error, HttpRequestMessage request)
{
_error = error;
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var err = new Error()
{
Code = _error.Code,
Message = _error.Message
};
var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new ObjectContent<Error>(err, new JsonMediaTypeFormatter()),
RequestMessage = _request
};
return Task.FromResult(response);
}
}
public class Error
{
public string Code { get; set; }
public string Message { get; set; }
}
然后使用它:
var err = new Error()
{
Code = "400",
Message = "Failed Invalid Product Id"
};
return new ErrorResult(err, Request);
這將錯(cuò)誤返回:
- 1 回答
- 0 關(guān)注
- 149 瀏覽
添加回答
舉報(bào)