2016-09-24 31 views

回答

1

您可以將app.UseStatusCodePagesWithReExecuteapp.UseStatusCodePagesWithRedirect添加到管道中(在app.UseMvc之前)。這將截取狀態代碼在400和600之間的任何響應,即尚未有身體

在啓動類:

app.UseStatusCodePagesWithReExecute("/statuscode/{0}"); 

然後添加一個新的控制器:

public class HttpStatusController: Controller 
{ 
    [HttpGet("statuscode/{code}")] 
    public IActionResult Index(HttpStatusCode code) 
    { 
     return View(code); 
    } 
} 

,並添加視圖查看/的HTTPStatus/Index.cshtml:

@model System.Net.HttpStatusCode 
@{ 
    ViewData["Title"] = "Error " + (int)Model; 
} 

<div class="jumbotron"> 
    <h1>Error @((int)Model)!</h1> 
    <p><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></p> 
</div> 

現在你只需要從控制器返回所需的狀態代碼,而無需添加任何可選主體:

//These would end up in the new HttpStatus controller, they just specify the status code 
return StatusCode(404); 
return new StatusCodeResult(404); 

//Any of these won't, as they add either the id or an object to the response's body 
return StatusCode(404, 123); 
return StatusCode(404, new { id = 123 }); 
return new NotFoundObjectResult(123); 
相關問題