Roman Pushkin
Roman Pushkin

Reputation: 6079

Elegant way of avoiding ASP.NET MVC routing errors

I have a route:

        routes.MapRoute("ResetPasswordConfirm", "reset-password-confirm", new { controller = "Membership", action = "ResetPasswordConfirm" });

and the code

    public ActionResult ResetPasswordConfirm(int userid, string key)
    {
        // ...
    }

in my application. So that i have url to be executed like this:

http://localhost/reset-password-confirm?userid=1&key=bla_bla_something

That is absolutely okay, until someone decides to go to

http://localhost/reset-password-confirm

...and look what will happen. ASP.NET will generate predictable error:

The parameters dictionary contains a null entry for parameter 'userid' of non-nullable type 'System.Int32'...

It could be done also by a search robot trying to grab all the possible urls. It's okay, but generates a lot of errors during usage of application in the wild. I want to avoid that, but feel uncomfortable with writing a stub for every possible case for such kind of errors.

Is there any elegant way of doing that? Thanks.

Upvotes: 1

Views: 149

Answers (2)

danielQ
danielQ

Reputation: 2086

Another way is to handle global errors, just set <customErrors mode="On"></customErrors> on your web.config and create an Error.cshtml on your Shared view folder. MVC3 templates actually include that page.

On the other hand, if you want to be more specific, you should try Action Filters, that's a cool way to handle errors.

[HandleError(View = "YourErrorView", ExceptionType=typeof(NullReferenceException))]
public ActionResult ResetPasswordConfirm(int? userid, string key)
{
      if (!userid.HasValue)
         throw new NullReferenceException();
      // ...
}

Upvotes: 2

Paolo del Mundo
Paolo del Mundo

Reputation: 2121

Use nullables for your parameters, i.e.:

public ActionResult ResetPasswordConfirm(int? userid, string key)

Upvotes: 1

Related Questions