Search code examples
c#http-redirectdetectasp.net-core-1.1request-uri

Detect requstURI dynamically + ASP.NET Core


I'm using web.config to set up some rediretion rules using .Net Core.

<rule name="About Page" stopProcessing="true">
    <match url="about.aspx" />
        <action type="Redirect" url="/Home/About" redirectType="Permanent" />
</rule>
...

So if the user enters www.test.com/about.aspx, it redirects to www.test.com/Home/About page.

My question is how can I pass what the user entered in URL to the controller method? For example, www.test.com/about.aspx in this case?

I tried with

var currentURI = new Uri($"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}");

But that one detects the redirected uri (www.test.com/Home/About), not the initially typed in URL (www.test.com/about.aspx)

I'm using the below code in HomeController, IActionResult About method.

using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, uri))

HttpRequestMessage's requestUri parameter is not dynamic at the moment, so it won't be able to detect what the user entered in URL.

Help is appreciated.


Solution

  • Let's describe the flow of HTTP requests for more clarity:

    1. HTTP Client sends initial request to http://www.test.com/about.aspx
    2. Your redirect rule hits and server responds with 301 code and redirect URL http://www.test.com/Home/About in Location header.
    3. HTTP Client receives this response and realizes that it should resend request with new URL
    4. HTTP Client sends second request to new URL http://www.test.com/Home/About.

    Second request does not contain any reference to original url http://www.test.com/about.aspx. That's why there is no way for you to get original url on server side.

    If your application logic requires having info about initial url, I see two options here:

    1. You could add original url as a parameter to redirected url, something like this: http://www.test.com/Home/About?orig_url=http://www.test.com/about.aspx

      You have to update redirection rule with new template and also adjust routing in ASP.Net Core application.

    2. You could use routing instead of redirection. In this case no 301 redirect will happen, Server will process initial request with the url typed by user, but the same Controller action will be called for both urls.

    Choose the approach that is more suitable for you. Hope this will help.