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.
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With