方法返回HttpResponseMessage -我如何返回一个异常,这是可能的吗?



我正在使用ASP。净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与状态代码的任何我想要的,但我想返回一个异常。我知道关于HttpResponseException,但这需要一个HttpResponseMessage,所以我回到了原点。是否可能返回异常?

你需要抛出一个HttpResponseException和一个正确创建的ErrorResponse,如下所示:

throw new HttpResponseException(Request.CreateErrorResponse(
    HttpStatusCode.BadRequest, // Use the right status code
    "OMG, I like totally FAILED."));

相关内容

  • 没有找到相关文章

最新更新