Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

How can I return a 404 status code by app.UseStatusCodePages?

$
0
0

These days I am handling 404 Not Found by Asp.Net Core .

As we know, there are several ways to achieve this: app.UseStatusCodePagesWithRedirects/app.UseStatusCodePagesWithReExecute/app.UseStatusCodePages .

I have to choose the app.UseStatusCodePages for I need to localizer the page by URL.

For example:

https://www.microsoft.com/en-us/microsoft-365/

The 'en-us' in URL just for deciding the language of the page.

Here is my code in startup.cs

app.UseStatusCodePages(async context =>
            {
                string currentCulture = "";
                if (context.HttpContext.Request.Path.Value.Split('/').Length < 2)
                {
                    currentCulture = "en";
                }
                else
                {
                    string LanguageGet = context.HttpContext.Request.Path.Value.Split('/')[1];
                    currentCulture = SupportedCultures.Find(X => X.Name == LanguageGet) == null ? "en" : SupportedCultures.Find(X => X.Name == LanguageGet).Name;
                }
                var redirectPath = "/" + currentCulture + "/Error/" + context.HttpContext.Response.StatusCode;
                context.HttpContext.Response.Redirect(redirectPath);
            });

Now it works.

However, after I input a URL which does not exist. The header shows a 302 status code in the Network of Chrome DevTools but not a 404 status code.

Well, when I input the URL(https://www.microsoft.com/en-us/123.html), the header shows a right 404 status code in the Network of Chrome DevTools.

I searched about this on Google. Someone said I should add a ProducesResponseType in the controller, just like this:

public class OthersController : Controller
    {
        [Route("{culture=en}/Error/{code:int}")]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public IActionResult Error(int code)
        {            
            return View(code);
        }
    }

Well, it doesn't work any. I want to solve this because of SEO.

How can I solve this? Thank you.


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>