Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core and CreateErrorResponse

I want to return invalid ModelState from my API method and try to use as it was in Web Api:

            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Test");

but it says, that

Severity Code Description Project File Line Suppression State Error CS1929 'HttpRequest' does not contain a definition for 'CreateErrorResponse' and the best extension method overload 'HttpRequestMessageExtensions.CreateErrorResponse(HttpRequestMessage, HttpStatusCode, string)' requires a receiver of type 'HttpRequestMessage'

So, something changed in ASP.NET Core and I should include HttpRequestMessage as first parameter. But how to create it and why it's necessary in response at all?

EDIT:

I found, that invalid model can be returned by the following code:

return HttpBadRequest(ModelState);

but in any case, want to know flexible method to return my own error responses.

like image 650
Oleg Sh Avatar asked Mar 12 '16 20:03

Oleg Sh


1 Answers

I found mono had not implemented these either; System.Web.Http/HttpRequestMessageExtensions adds extension methods to System.Net.Http. You could do it yourself

namespace System.Web.Http
{
    public static class ApiControllerExtensions
    {
        [System.Xml.Serialization.XmlRoot(ElementName = "Error", Namespace = "")]
        public class ErrorResponse
        {
            public string StatusCode { get; set; }
            public string Message { get; set; }
        }
        public static HttpResponseException CreateErrorResponseException(this ApiController controller, HttpStatusCode statusCode, string message)
        {
            ErrorResponse error = new ErrorResponse() 
            { 
                StatusCode = (int)statusCode + ": " + statusCode.ToString(),
                Message = message 
            };
            HttpResponseMessage responseMessage = controller.Request.CreateResponse(statusCode, error, controller.Request.GetConfiguration());
            return new HttpResponseException(responseMessage);
        }
    }
}
like image 147
KCD Avatar answered Nov 14 '22 22:11

KCD