I'm using ASP.NET WebAPI2. Here's my code:

[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();
                }
    }

I would like to do something like shown above - return an Exception indicating an error. I understand I can return an HttpResponseMessage with a status code of whatever I'd like, but I would like to return an Exception. I know about HttpResponseException, but this takes in an HttpResponseMessage, so I'm back to square one. Is returning an exception possible?

有帮助吗?

解决方案

You need to throw an HttpResponseException with a properly created ErrorResponse as below:

throw new HttpResponseException(Request.CreateErrorResponse(
    HttpStatusCode.BadRequest, // Use the right status code
    "OMG, I like totally FAILED."));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top