Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net core, redirect to a static html page if URL has Https

Redirect to a static html page if the url contains "https"

After accepting the warning "Not trusted (Since using https)". I would like to redirect the users to a static page with some useful message.

Https connection wont fail, I just dont want to load application if its a Https request. I want to load a static Html page instead.

Ex: https://localhost:1234 then redirect to a static page

Right Now What I have:

if the url is http://localhost:3221 it redirects to HomeController -> Index Action

It is more like adding conventional routing for Https request, I dont know if it is possible.

like image 408
Dot Net Dev Avatar asked Sep 08 '25 02:09

Dot Net Dev


1 Answers

You can write a simple middleware for this. Something like this should do the job:

app.Use(async (context, next) =>
{
    // check if the request is *not* using the HTTPS scheme
    if (!context.Request.IsHttps)
    {
        // redirect to some relative URL (see note below!)
        context.Response.Redirect("/no-https-error.html");

        return;
    }

    // otherwise continue with the request pipeline
    await next();
});

Since this is a middleware it affects every requests that reach the middleware at the point you have inserted into the pipeline. So if you would place this before app.UseStaticFiles(), then this middleware will also prevent you from reaching static files, including that error file you redirect to. If you want to do that, you would have to make the redirect contain an absolute path to a http:// address instead:

var url = "http://" + context.Request.Host + context.Request.PathBase + "/no-https-error.html";
context.Response.Redirect(url);
like image 167
poke Avatar answered Sep 10 '25 12:09

poke