我正在使用ASP.NET WebAPI2。这是我的代码:
[HttpPost]
public HttpResponseMessage SaveNewPdf(HttpRequestMessage req)
{
var json = req.Content.ReadAsStringAsync().Result;
NewFile newFile = JsonConvert.DeserializeObject<NewFile>(json);
string error = string.Empty;
// check all the foreign key values to ensure they are valid
var isArticleCategoryValid = HelperClasses.ForeignKeyChecks.IsArticleCategoryValid(newFile.ArticleCategory);
var isDocumentTypeValid = HelperClasses.ForeignKeyChecks.IsDocumentTypeValid(newFile.DocumentType);
var isActionPublisherValid = HelperClasses.ForeignKeyChecks.IsActionPublisherValid(newFile.ActionPublisher);
var isRuleComplianceValid = HelperClasses.ForeignKeyChecks.IsRuleComplianceValid(newFile.RuleCompliance);
if (!isArticleCategoryValid)
{
error = "articleCategory in the JSON is not a valid Article Category";
return new HttpResponseException();
}
}
我想做一些如上所示的事情 - 返回一个表示错误的异常。我知道我可以返回一个HttpResponseMessage,其状态代码是我想要的,但我想返回一个Exception。我知道HttpResponseException,但这需要一个HttpResponseMessage,所以我回到原点。是否可以返回异常?
答案 0 :(得分:5)
您需要使用正确创建的ErrorResponse抛出HttpResponseException,如下所示:
throw new HttpResponseException(Request.CreateErrorResponse(
HttpStatusCode.BadRequest, // Use the right status code
"OMG, I like totally FAILED."));