MVC Controller return a bad request?

别说谁变了你拦得住时间么 提交于 2019-12-04 22:13:45
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");
    }
}
Massood Khaari

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>

...

Basheer AL-MOMANI

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

  1. to return HttpStatusCodeResult(HttpStatusCode.BadRequest); in case user does not provided a required value

  2. to return HttpNotFound(); in case the user provided a required value but not veiled

hope this help you

Ekk

You can pass in error message to the second parameter like so:

return new HttpResponseMessage(HttpStatusCode.BadRequest, "Your message here");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!