1 回答
TA贡献1859条经验 获得超6个赞
你可以做这样的事情,没有测试它:
return Content((HttpStatusCode)400, "Failed Invalid Product Id");
如果你真的想有自定义的方式来做到这一点,那么你需要IHttpActionResult用你自己的类来扩展实现,就像下面的例子一样,它是从这个链接中得到启发的:
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);
这将错误返回:
- 1 回答
- 0 关注
- 111 浏览
添加回答
举报