Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Controller return a bad request?

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;         } } 
like image 548
Dr Schizo Avatar asked Jul 08 '15 08:07

Dr Schizo


People also ask

What does ActionResult return?

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.

What is BadRequest in C#?

BadRequest(ModelStateDictionary)Creates an InvalidModelStateResult (400 Bad Request) with the specified model state. C# Copy. [Microsoft.AspNetCore.Mvc.NonAction] public virtual System.Web.Http.

What is return type of ActionResult in MVC?

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.

What is HttpStatusCodeResult?

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.


2 Answers

return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "naughty"); 
like image 53
Ian Avatar answered Sep 19 '22 12:09

Ian


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");     } } 
like image 23
ShankarSangoli Avatar answered Sep 21 '22 12:09

ShankarSangoli