views:

162

answers:

4

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
  }
+2  A: 

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.

Martin
Why? profileKey should be 5 in my example not null?
Dan
It would allow the route to work correctly. Then all you would need to do is, inside the action do profileKey.HasValue. If it is, then you have an int. Otherwise, you can either redirect elsewhere, or throw an error.
Dan Atkinson
This answer tell mes how to stop the exception which is the wrong approche. The exception shouldnt happen in the first place if the routing is done right.
Dan
A: 

Is that your only route? If not, maybe another route (declared earlier) is matching first, and isn't picking up the profileKey parameter properly.

Mike Powell
I read it could be this, so iv commented out all the other routes, so I only have this one, and then the default. But it didnt help.
Dan
A: 

Try this (untested) code

routes.MapRoute(
    "Profile", "Profile/{profileKey}", 
    new { controller = "Profile", action = "PublicView" }
);
Canton
No that cause the same exception. The best I can come up with is routes.MapRoute("Profile", "Profile", new { controller = "Profile", action = "PublicView" }); but this produces a url of example.com/profile?profileKey=5, which still isnt perfect.
Dan
I tested it should work. Would you post your method signature?
Canton
+1  A: 
Kurt Schindler