MVC 控制器 return 一个错误的请求?

MVC Controller return a bad request?

我想知道是否可以 return 一个包含来自 MVC 控制器的内容的错误请求?我能够做到这一点的唯一方法是 throw HttpException 但是在这里我无法设置任何内容。尝试过这种方法,但出于某种奇怪的原因,我总是得到 OK。可以这样做吗?

public class SomeController : Controller
{
    [HttpPost]
    public async Task<HttpResponseMessage> Foo()
    {
        var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
        response.Content = new StringContent("Naughty");

        return response;    
    }
}

您可以像这样将错误消息传递给第二个参数:

return new HttpResponseMessage(HttpStatusCode.BadRequest, "Your message here");

将 Http 状态代码设置为错误请求并使用 Content 方法发送您的内容和响应。

public class SomeController : Controller
{
    [HttpPost]
    public async Task<ActionResult> Foo()
    {
        Response.StatusCode = 400;
        return Content("Naughty");
    }
}

除了@Ekk 的,一定要检查这个:

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>

...

return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "naughty");

当然可以。

看看我的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);
}

我认为这是最佳做法

  1. 到returnHttpStatusCodeResult(HttpStatusCode.BadRequest);以防用户未提供所需的值

  2. 到 return HttpNotFound(); 如果用户提供了所需的值但没有隐藏

希望对您有所帮助

TrySkipIisCustomErrors 标志可用于关闭 IIS 自定义错误处理。

[HttpGet]
public void Foo()
{
  HttpContext.Response.TrySkipIisCustomErrors = true;
  HttpContext.Response.StatusCode = 400;
  HttpContext.Response.Write("Naughty");
}