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
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 andBeginRequest
in your particular case.HttpRequest
object in these events should contains initial URL.For more information:
IIS URL Rewriting and ASP.NET Routing
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 hookBeginRequest()
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
: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)