5

When you manipulate data in an action, you often receive an ID as param, but you need to do some error handling for that id. One of the error handling you have to do for every action is to make sure the ID is higher than 0 (not a negative number). So instead of handling this in the action, I wanted to add a route constraint so just doesnt route to the action if its a negative id.

Here's my code:

//route definition
        routes.MapRoute(
            "default route" ,
            "{controller}/{action}/{id}" ,
            new { id = UrlParameter.Optional },
            new { id = @"^\d+$" }
        );

//action definition (note I also tried with only [HttpPost] and with nothing same result
        [AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get )]
        public ActionResult Edit( int id )

It all works fine when you do a GET on the action, but when I POST I get the following error when it should just go to the 404 page

 HTTP verb POST used to access path '/object/edit/-2' is not allowed.

[HttpException (0x80004005): The HTTP verb POST used to access path '/object/edit/-2' is not allowed.]
   System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state) +740
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +632
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +194

Any ideas? Perhaps a better solution?

EDIT: Just noticed something interesting, I initially thought that the error message was a 500, but its a 405 which is "method not found"

tereško
  • 58,060
  • 25
  • 98
  • 150
Pierluc SS
  • 3,138
  • 7
  • 31
  • 44

3 Answers3

1

You say:

HTTP verb POST used to access path '/object/edit/-2' is not allowed.

However the exception states:

The HTTP verb POST used to access path '/profile/editlink/-2' is not allowed.

Edit:

I think this might be related to your problem.

However it isn't as you state.

Ropstah
  • 17,538
  • 24
  • 120
  • 194
1

I highly suggest installing the routing debugger found here. It'll show you exactly how a given URL is being parsed by each route, so you can see what's really happening when you hit that URL. If your route is being skipped, then you know your constraint is working, and you can focus on whatever is catching it. If your route is being hit, then it's a problem with the action and/or the verbs it takes.

Side note: I utterly failed to get the 2.0.0.7 version of this debugger working correctly (back in August), but the one linked directly in the article (or the 1.0.0.1 version on NuGet) worked fine. I would assume that the current version in NuGet is working, but if not, try the older version.

Bobson
  • 13,498
  • 5
  • 55
  • 80
0

Try removing

[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get )]

And see if it just works (usually you would put [HttpPost] to deny HttpGet etc).

Andrew
  • 1,606
  • 1
  • 12
  • 19