I was wondering if it was possible to return a bad request with content from an MVC Controller? The only way I have been able to do this is to throw HttpException
however here I can't set any content. Tried this approach to but for some odd reason I am always getting an OK back. Is it possible to do this?
public class SomeController : Controller { [HttpPost] public async Task<HttpResponseMessage> Foo() { var response = new HttpResponseMessage(HttpStatusCode.BadRequest); response.Content = new StringContent("Naughty"); return response; } }
An action result is what a controller action returns in response to a browser request. The ASP.NET MVC framework supports several types of action results including: ViewResult - Represents HTML and markup. EmptyResult - Represents no result.
BadRequest(ModelStateDictionary)Creates an InvalidModelStateResult (400 Bad Request) with the specified model state. C# Copy. [Microsoft.AspNetCore.Mvc.NonAction] public virtual System.Web.Http.
An ActionResult is a return type of a controller method in MVC. Action methods help us to return models to views, file streams, and also redirect to another controller's Action method.
HttpStatusCodeResult(HttpStatusCode, String) Initializes a new instance of the HttpStatusCodeResult class using a status code and status description. HttpStatusCodeResult(Int32) Initializes a new instance of the HttpStatusCodeResult class using a status code.
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "naughty");
Set the Http status code to bad request and use Content
method to send your content along with response.
public class SomeController : Controller { [HttpPost] public async Task<ActionResult> Foo() { Response.StatusCode = 400; return Content("Naughty"); } }
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