Click here to Skip to main content
15,883,705 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
Hi,

how to execute MVC web api method with different name but type is GET and POST. i can't able to execute. it shows error. here is my code.

webapiconfig.cs

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



Employee controller :

C#
[HttpGet]
      public string Test1()
      {
          return "this is a string";
      }

      [HttpGet]
      public string Test2()
      {
          return "this is a another string";
      }
   [HttpPost]
        public string Test3()
        {
            return "this is a another post string";
        }


i want to execute all this method in different scenario. how to do it?
Posted

Add two or more route to the config. So you call api method by using name like below
C#
config.Routes.MapHttpRoute(
            name: "ApiByName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }
           );
          config.Routes.MapHttpRoute(
              name: "ApiByAction",
              routeTemplate: "api/{controller}/{action}",
              defaults: new { action = "Get" }
          );
          config.Routes.MapHttpRoute(
              name: "DefaultApi",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { id = RouteParameter.Optional }
          );


Hope this helps
 
Share this answer
 
C#
config.Routes.MapHttpRoute(
               name: "Default",
               routeTemplate: "controller/{action}/{id}",
               defaults: new { controller="Employee" action = "test1", id = RouteParameter.Optional }
               );


You didn't mention controller.
[httpget],[httppost] are get differentiate with parameter.
You are not suppose to register all the route. Only default one is required.
Later application manage by clicking on different links.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900