以下の例のコントローラーに、内容のないステータスコード418を返すようにします。ステータスコードの設定は簡単ですが、リクエストの終了を知らせるために何かする必要があるようです。 ASP.NET Core以前のMVCやWebFormsではResponse.End()
への呼び出しになる可能性がありますが、Response.End
が存在しないASP.NET Coreではどのように機能しますか?
public class ExampleController : Controller
{
[HttpGet][Route("/example/main")]
public IActionResult Main()
{
this.HttpContext.Response.StatusCode = 418; // I'm a teapot
// How to end the request?
// I don't actually want to return a view but perhaps the next
// line is required anyway?
return View();
}
}
this.HttpContext.Response.StatusCode = 418; // I'm a teapot
リクエストを終了する方法
他の解決策を試してください。
return StatusCode(418);
HTTPステータスコードを返すためにStatusCode(???)
を使うことができます。
また、専用の結果を使用することもできます。
成功:
return Ok()
←HTTPステータスコード200return Created()
←HTTPステータスコード201return NoContent();
←HTTPステータスコード204クライアントエラー:
return BadRequest();
←HTTPステータスコード400return Unauthorized();
←HTTPステータスコード401return NotFound();
←HTTPステータスコード404
詳細:
誰かがIHttpActionResult
を使用してこれを実行したい場合は、Web APIプロジェクトに含まれている可能性があります。以下が役立ちます。
// GET: api/Default/
public IHttpActionResult Get()
{
//return Ok();//200
//return StatusCode(HttpStatusCode.Accepted);//202
//return BadRequest();//400
//return InternalServerError();//500
//return Unauthorized();//401
return Ok();
}
このコードは、.NET以外のCore MVCコントローラでも機能する可能性があります。
this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);