skip to Main Content

Using IIS, we’re currently redirecting URLs. But to display canonical URL’s in the site for SEO, we want the original URL.

Example:
Actual URL: www.example.com/topsellers/mobiles
Redirected URL: www.example.com/products?type=mobiles

IIS Rewrite Rules:

<rule name="url1" stopProcessing="true">
            <match url="topsellers/([a-zA-Z0-9]+)" />
            <action type="Rewrite" url="products?type={R:1}" />
        </rule>

Is there a way in C# to get the Actual URL in the controller?

I have tried using HttpContext.Current.Request, HttpRequest, and many other objects from C#, but couldn’t access the required one. Can anyone help me out with this, if there’s any solution?

Technology Stack being used: ASP NET CORE V2.2.1

3

Answers


  1. You won’t find it in the controller since rules are processed starting with the server level on down to the site and subfolders. URL Rewrite itself is processed very early in the IIS pipeline, before most IIS-related functionality.

    But you can try to check two events: PreBeginRequest for global rules and BeginRequest in your particular case. HttpRequest object in these events should contains initial URL.

    For more information:
    IIS URL Rewriting and ASP.NET Routing

    Login or Signup to reply.
  2. Instead of using IIS rewrite rules, what you want to do is to implement a custom IHTTPModule that takes care of the rewrites (and strip our the rewrite rules from web.config.

    You’ll need to implement the Init() method to set it up, and hook BeginRequest() where you’ll have access to the original request and you can redirect it, rewrite it, or otherwise handle it as you see fit. Or do nothing and pass it along.

    One you have implemented it, you just wire it up into the stack in web.config:

    <system.web>
      <httpModules>
        <add type="Nordstrom.Web.External.HttpsSupport.HttpsFilter, Nordstrom.Web.External" name="HttpsFilter" />
        <add type="Nordstrom.Web.External.InternationalShopModule, Nordstrom.Web.External" name="IntlShipModule" />
        <add type="Nordstrom.Web.External.RequestManager, Nordstrom.Web.External" name="RequestHandler" />
      </httpModules>
      . . .
    </system.web>
    
    Login or Signup to reply.
  3. @using Microsoft.AspNetCore.Http.Features
    
    @{var path = Context.Request.HttpContext.Features.Get<IHttpRequestFeature>().RawTarget.ToString();}
    

    This is how I was able to get the actual URL that the user can see in the address bar after a rewrite to a different page/URL. (This is written in a Razor .cshtml view)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search