Angular Application Returning 200 instead of 404

2 replies
How to catch and show routing error header response, as i am getting 200 instead of 404 when redirecting to not found page. I want 404 header response when redirecting to not found page. (edited to remove link)
#200 #404 #angular #application #returning
  • Profile picture of the author Benito13
    how can I access the 404

    Yes definitely a better one for 404
    {{ DiscussionBoard.errors[11677175].message }}
  • Profile picture of the author WF- Enzo
    Administrator
    This might help

    // Wherever you want to return your standard 404 page
    return Redirect("Home/StatusCode?code=404");
    public class HomeController : Controller
    {
    // This method allows for other status codes as well
    public IActionResult StatusCode(int? code)
    {
    // This method is invoked by Startup.cs >>> app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}");
    if (code.HasValue)
    {
    // here is the trick
    this.HttpContext.Response.StatusCode = code.Value;
    }
    //return a static file.
    try
    {
    return File("~/" + code + ".html", "text/html");
    }
    catch (FileNotFoundException)
    {
    return Redirect("Home/StatusCode?code=404");
    }
    }
    }
    This does return 404.
    Solution 2:
    Create a Utilities class to return the 404 code and 404.html.
    In the HomeController, I have the StatusCode IActionResult.
    // This method is invoked by Startup.cs >>> app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}");
    public IActionResult StatusCode(int? code)
    {
    // Call the static method
    return Utilities.StatusCode(code: code.Value, this.HttpContext);
    }
    In Models, I've added a Utilities.cs.
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Http;
    using System.IO;
    namespace MediaMgt.Models
    {
    public static class Utilities
    {
    public static IActionResult StatusCode(int code, HttpContext httpContext)
    {
    // here is the trick
    httpContext.Response.StatusCode = code;
    //return a static file.
    try
    {
    return new VirtualFileResult("~/" + code + ".html", "text/html");
    }
    catch (FileNotFoundException)
    {
    httpContext.Response.StatusCode = 404;
    return new VirtualFileResult("~/404.html", "text/html");
    }
    }
    }
    }
    Signature
    {{ DiscussionBoard.errors[11686633].message }}

Trending Topics