MVC Controller return a bad request?
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 valueto return
HttpNotFound();
in case the user provided a required value but not veiled
hope this help you
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>
...
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");
}
}
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "naughty");