Dr *_*izo 37 c# asp.net-mvc bad-request asp.net-mvc-4
我想知道是否有可能从MVC控制器返回一个带有内容的错误请求?我能够做到这一点的唯一方法是在throw HttpException这里我不能设置任何内容.试过这种方法,但由于一些奇怪的原因,我总是得到回报.是否有可能做到这一点?
public class SomeController : Controller
{
[HttpPost]
public async Task<HttpResponseMessage> Foo()
{
var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
response.Content = new StringContent("Naughty");
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
Ian*_*Ian 77
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "naughty");
Run Code Online (Sandbox Code Playgroud)
Sha*_*oli 17
将Http状态代码设置为错误请求,并使用Content方法将内容与响应一起发送.
public class SomeController : Controller
{
[HttpPost]
public async Task<ActionResult> Foo()
{
Response.StatusCode = 400;
return Content("Naughty");
}
}
Run Code Online (Sandbox Code Playgroud)
Mas*_*ari 11
除了@Ekk的答案,请务必检查:
ASP.NET + Azure 400错误请求不返回JSON数据
将以下条目添加到"web.config".
Run Code Online (Sandbox Code Playgroud)<system.webServer> <httpErrors existingResponse="PassThrough"/> </system.webServer>...
当然可以.
看看我的行动吧
// 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);
}
Run Code Online (Sandbox Code Playgroud)
我认为这是最好的做法
返回HttpStatusCodeResult(HttpStatusCode.BadRequest);的情况下,用户没有提供必需的值
返回HttpNotFound();的情况下,用户提供所需的值,但不遮掩
希望这能帮助你
| 归档时间: |
|
| 查看次数: |
58414 次 |
| 最近记录: |