ASP.Net MVC:How to rewrite url by middleware in ASP.NET Core
<p>In asp.net 4.0 we can use work with the http module to rewrite module like so:</p>

<pre><code>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 &gt;= 2)
    {
        CountryCodeInUrl = HttpContext.Current.Request.RawUrl.Substring(1, 2);
    }

    if (countryCode != CountryCodeInUrl)
    {
        if (HttpContext.Current.Request.RawUrl.Length &gt;= 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);
    }   
}
</code></pre>

<p>How could I rewrite the code above using middleware in ASP.NET Core?</p>

<p>I have just partially read this article:
<a href="https://docs.microsoft.com/en-us/aspnet/core/migration/http-modules" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/aspnet/core/migration/http-modules</a></p>