Lobsterpants
Lobsterpants

Reputation: 1258

Asp.net MVC routing for old aspx Url

We used to have some webforms setup that allowed us to edit jobs. External applications would access them using a URL like this:

http://server/EditJob.aspx?JobID=1235

having replaced the webforms with MVC the new URL is

http://server/MVC/Jobs/Edit/1235 

I would like calls to the former Url to be routed to the new URl as changing the clients is not possible. How can I achieve this?

I tried:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(name: "Job Link", url: "EditJob.aspx?JobID ={JobID}", defaults: new { area = "MVC", controller = "Jobs", action = "Edit" });

        routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new { area = "MVC", controller = "Jobs", action = "Index", id = UrlParameter.Optional });
    }

But this gives a (System.ArgumentException: 'The route URL cannot start with a '/' or '~' character and it cannot contain a '?' character.'

So, can I do this using routing or should I recreate the old webforms as redirections to the new pages.

thanks

Update

Thanks to all you clever people I have discovered the wonderful world of IIS URL rewriting which seems to do exactly what I need.

I now have this rule inplace which is close to what I want:

   <rewrite>
  <rules>
    <rule name="Jobs page redirect" stopProcessing="true">
      <match url="EditJob.aspx" />
      <conditions>
        <add input="{QUERY_STRING}" pattern="JobID=(\d+)" />
      </conditions>
      <action type="Redirect" redirectType="" url="MVC/Jobs/Edit/{C:1}" appendQueryString="false" />
    </rule>
  </rules>
</rewrite>

But this redirects to:

 /MVC/Jobs/Edit/1235?JobID=1235

It would seem appendQueryString="false" doesn't work or am I missing something ?

Upvotes: 5

Views: 1255

Answers (1)

Tim
Tim

Reputation: 4257

I would do this using the IIS rewrite module if you can. That way you keep any logic for your old URLs out of the new app, and if you need to tweak the rules, you can just tweak the web.config file instead having to recompile the site.

If your server doesn't already have the module installed, you can get it from the links on this page: https://learn.microsoft.com/en-us/iis/extensions/url-rewrite-module/using-the-url-rewrite-module (you can also use the IIS Web Platform Installer).

You should be ablate create a regular expression rule to redirect the old URLs to the new one. You can easily add rules for any other legacy URLs as well if need be :)

Upvotes: 2

Related Questions