Question

I am writing a implementing a ASP.NET web app, and when I call against a particular url, I want to call a different action method depending on whether the request is a GET or a POST.

I've tried two different approaches - first of all I start with a controller with the following action methods:

<HttpGet>
Public Function Index() as ActionResult
...
End Function

<HttpPost>
Public Function Index() as ActionResult
...
End Function

... and then registering a Route which sets .action to "Index" for the Url. This doesn't compile, because the two functions have the same signature.

Next I tried changing the name of the Post routine to "Subscribe", but of course that would require me to supply two different routes to the routing table (so as to specify the new action method name). If I do that, I find that the second one is cancelled out by the first.

I'm now thinking of going back to my original idea, but supplying a dummy parameter to it, and specifying it as UrlParameter.Optional. By having this as an argument in the post routine, this will create a new method signature, which I would expect would be ok.

It smells a bit of a dirty hack though - so I was wondering how other people would go about it?

Martin.

Ps. I have now tried the dirty hack, and it does work. Still interested in hearing the views of others though.

Was it helpful?

Solution

Rename actions and use ActionNameAttribute

<HttpGet>
<ActionName("Index")>
Public Function IndexGet() as ActionResult
...
End Function

<HttpPost>
<ActionName("Index")>
Public Function IndexPost() as ActionResult
...
End Function

But I don't know what your POST method will do because it doesn't get any data. POST actions usually get some post data to process, so it would probably need some parameters as well. When you'd add them your two methods could share the same name since their signatures would differ (one would be without parameters, and one with them).

OTHER TIPS

Just a short note to highlight the actual approach I took in the end - although Robert's answer above is perfectly valid as well...

I ended up using a ".httpMethodConstraint" attribute on the constraint argument of the MapRoute function, and then provided separate routes for the various method types involved.

Robert's solution is, I think, generally a better approach to take - but for my specific problem taking an approach of mapping distinct routes is the preferred solution of my tech lead.

There's not a lot in it - except if I were working on a big site I would have reservations about creating loads and loads of Routes, as they can get confusing quickly.

Cheers for the help...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top