Reputation: 2994
My project has a 404 page already. I set it by the app.UseStatusCodePages()
in startup.cs
and it works well.
Now I have a controller:
[Route("{id:int}.html")]
public IActionResult Test(int id)
{
var A=///some logic;
if(A!=null)
{
return View(A);
}
else
{
return NotFound();
}
}
Well, if the A is null, the browser only returns a This localhost page can’t be found
page while not the 404 pages.
I don't want to use something redirect method, for it will return a 302 code while not only a 404 code.
How can I solve this? Thank you.
Upvotes: 1
Views: 3733
Reputation: 4839
You could specify the path to your 404 page when returning a View
.
e.g. return View("~/Views/Error/404.cshtml");
If you want to use it multiple times, I would suggest putting it in a function in a base class.
protected IActionResult 404View() {
return View("~/Views/Error/404.cshtml");
}
NotFound
returns a status code rather than a view, as explained in the summary
Creates an Microsoft.AspNetCore.Mvc.NotFoundResult that produces a Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound
If you want to return a 404 status code and a View, you can just set the status code on the response before returning the View as described in How to return 404 with asp.net mvc view.
Response.StatusCode = 404;
return View("~/Views/Error/404.cshtml");
Upvotes: 3