Reputation: 4362
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;
}
}
Upvotes: 83
Views: 123867
Reputation: 1294
Answer for .Net Core: Return IActionResult
as documented here. For example:
public IActionResult Get(int id = 0)
{
try
{
var obj = _myRepo.Get(id);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
return Ok(obj);
}
Upvotes: 2
Reputation: 11
The TrySkipIisCustomErrors flag can be used to turn off IIS custom error handling.
[HttpGet]
public void Foo()
{
HttpContext.Response.TrySkipIisCustomErrors = true;
HttpContext.Response.StatusCode = 400;
HttpContext.Response.Write("Naughty");
}
Upvotes: 1
Reputation: 3061
In addition to the @Ekk's answer, make sure to check this:
ASP.NET+Azure 400 Bad Request doesn't return JSON data
Add the following entry to your 'web.config'.
<system.webServer> <httpErrors existingResponse="PassThrough"/> </system.webServer>
...
Upvotes: 18
Reputation: 5715
You can pass in error message to the second parameter like so:
return new HttpResponseMessage(HttpStatusCode.BadRequest, "Your message here");
Upvotes: 4
Reputation: 15327
Of course you can.
Take a look at my Action
// GET: Student/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
I think this is best practice
to return HttpStatusCodeResult(HttpStatusCode.BadRequest);
in case user does not provided a required value
to return HttpNotFound();
in case the user provided a required value but not veiled
hope this help you
Upvotes: 9
Reputation: 3149
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "naughty");
Upvotes: 137
Reputation: 69905
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");
}
}
Upvotes: 30