Search code examples
asp.netasp.net-mvcasp.net-mvc-5asp.net-web-api2asp.net-mvc-routing

how to pass parameter name "action" in asp.net web api


Can not send parameter name "action" by url in asp.net web api 2.0.

Example:

http://host:port/controller_name?action=2&...

if you do so:

 config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{action}",
                defaults: new
                {
                    action=RouteParameter.Optional
                }
            );

method in controller:

   public HttpResponseMessage Get(int action)
    {
        return ResponseXml();
    }

gives an error message:

in the dictionary path name of the parameter "action" is contained in the URL-address more than once

How to pass parameter name "action" as a parameter, rather than the action method ?

thanks


Solution

  • Since the name action is included in the querystring part(?action=2), no need to change the route map. The framework will bind the value to the action paramter in the action method. Remove the extra {action} in routeTemplate. And since your url format doesn't contain {action} host:port/controller_name?action=2&login=, remove {action} from routemap. So, your route map will be

    config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{id}",
                defaults: new
                {
                    id=RouteParameter.Optional
                }
            );