Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC:How to rewrite url by middleware in ASP.NET Core

In asp.net 4.0 we can use work with the http module to rewrite module like so:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    string CountryCodeInUrl = "", redirectUrl="";
    var countryCode = CookieSettings.ReadCookie();
    if (countryCode=="")
    {
        countryCode = "gb";
    }

    if (HttpContext.Current.Request.RawUrl.Length >= 2)
    {
        CountryCodeInUrl = HttpContext.Current.Request.RawUrl.Substring(1, 2);
    }

    if (countryCode != CountryCodeInUrl)
    {
        if (HttpContext.Current.Request.RawUrl.Length >= 2)
        {
            if (HttpContext.Current.Request.RawUrl.Substring(1, 2) != "")
            {
                countryCode = HttpContext.Current.Request.RawUrl.Substring(1, 2);
            }
        }
        if(!System.Web.HttpContext.Current.Request.RawUrl.Contains(countryCode))
        {
            redirectUrl = string.Format("/{0}{1}", countryCode, System.Web.HttpContext.Current.Request.RawUrl);
        }
        else
        {
            redirectUrl = System.Web.HttpContext.Current.Request.RawUrl;
        }
        CookieSettings.SaveCookie(countryCode);
        System.Web.HttpContext.Current.Response.RedirectPermanent(redirectUrl);
    }   
}

How could I rewrite the code above using middleware in ASP.NET Core?

I have just partially read this article: https://docs.microsoft.com/en-us/aspnet/core/migration/http-modules

like image 240
Mou Avatar asked Dec 12 '16 13:12

Mou


People also ask

How do I redirect in middleware net core?

In a browser with developer tools enabled, make a request to the sample app with the path /redirect-rule/1234/5678 . The regular expression matches the request path on redirect-rule/(. *) , and the path is replaced with /redirected/1234/5678 . The redirect URL is sent back to the client with a 302 - Found status code.

What is URL rewriting in ASP NET MVC?

URL rewriting is the process of intercepting an incoming Web request and redirecting the request to a different resource. When performing URL rewriting, typically the URL being requested is checked and, based on its value, the request is redirected to a different URL.


1 Answers

You pretty much just need to move the code to a middleware class, and use the Core HttpContext instead of the System.Web one.

A class like that would look like this:

//RedirectMiddleware.cs

public class RedirectMiddleware
{
    private readonly RequestDelegate _next;

    public RedirectMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        string CountryCodeInUrl = "", redirectUrl = "";
        var countryCode = CookieSettings.ReadCookie();
        if (countryCode == "")
        {
            countryCode = "gb";
        }

        if (context.Request.Path.Value.Length >= 2)
        {
            CountryCodeInUrl = context.Request.Path.Value.Substring(1, 2);
        }

        if (countryCode != CountryCodeInUrl)
        {
            if (context.Request.Path.Value.Length >= 2)
            {
                if (context.Request.Path.Value.Substring(1, 2) != "")
                {
                    countryCode = context.Request.Path.Value.Substring(1, 2);
                }
            }
            if (!context.Request.Path.Value.Contains(countryCode))
            {
                redirectUrl = string.Format("/{0}{1}", countryCode, context.Request.Path.Value);
            }
            else
            {
                redirectUrl = context.Request.Path.Value;
            }
            CookieSettings.SaveCookie(countryCode);
            context.Response.Redirect(redirectUrl, true);
        }

        await _next.Invoke(context);
    }
}

To use it you then register it in you Startup.cs file, before you register the MVC middleware, like this:

app.UseMiddleware<RedirectMiddleware>();

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

I hope this'll get you started, you can see this blog post for more information on middleware.

like image 88
Tobias Avatar answered Oct 06 '22 02:10

Tobias