2016-09-24 26 views
2

NotFoundObjectResult結果のカスタムページを作成するにはどうすればよいですか?asp.netコアのNotFoundObjectResultのカスタムページ

実際にこの結果を返すと、アプリケーションはページ内のIDのみを表示します。

return new NotFoundObjectResult(id); 

NotFoundObjectResultを取得するたびに、「/ errors/notfound」にリダイレクトする必要があります。

答えて

1

app.UseStatusCodePagesWithReExecuteまたはapp.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);