R – Shortening URL params with MVC routing

asp.net-mvcasp.net-mvc-routingurl-routing

I have a url along the lines of this:

example.com/profile/publicview?profileKey=5

and I want to shorten it to this with routing

example.com/profile/5

How do I do this?

This is my attempt:

routes.MapRoute(
    "Profile", "Profile/{profileKey}", 
    new { controller = "Profile", action = "PublicView", profileKey ="" }
);

But his produces this error:

The parameters dictionary contains a
null entry for parameter 'profileKey'
of non-nullable type 'System.Int32'
for method
'System.Web.Mvc.ActionResult
PublicView(Int32)' in
'Website.Controllers.ProfileController

Action method

public ActionResult PublicView(int profileKey)
  {
        //stuff
  }

Best Answer

On the controller change the PublicView(int? profileKey)

ANSWER TO COMMENT

Yes, but since your default value in the route is null, you need to handle it. Otherwise, change the default in your route.

MAYBE

This probably won't help, but it is worth a try. Here is the code I have my site:

        routes.MapRoute(
            "freebies",                                              // Route name
            "freebies/{page}",                           // URL with parameters
            new { controller = "Home", action = "Freebies", page = 1 }  // Parameter defaults
        );

And the link:

http://localhost/freebies/2

And this works fine.

Related Topic