bluray
bluray

Reputation: 1963

ASP MVC routing rest api

i would like to create rest api but I have problem with routing. This url is ok: localhost/project/controller/action/id, but i would like this url localhost/project/controller/id too. For example: localhost/project/article/5: ArticleController.Get(int id) This is my code: Project controller

[HttpGet]
[Route("project/{id}")]
public JsonResult Get(int id)
{
}

Route config:

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

            routes.MapRoute(
                name: "Api",
                url: "{controller}/{id}",
                defaults: new { id = UrlParameter.Optional }
            );
        }

When i call url localhost/project/article/5, error message is A public action method '5' was not found on controller 'ArticleController'.

Where is problem? Thanks

Upvotes: 0

Views: 627

Answers (1)

Ashiquzzaman
Ashiquzzaman

Reputation: 5294

You can use attribute routing

Example:

[HttpGet]
[Route("project/{controller}/{action}/{id}")]
public JsonResult Get(int id)
{
}

OR

Default Route Table

Example:

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
            routes.MapRoute(
                name: "Api",
                url: "project/{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

        }

As Per your Requirement, your Routing is:

[HttpGet]
[Route("project/article/{id:int}")]
public JsonResult Get(int id)
{
}

OR

  routes.MapRoute(
                    name: "Api",
                    url: "project/article/{id}",
                    defaults: new { controller = "ArticleController", action = "Get", id = UrlParameter.Optional }
                );

Upvotes: 1

Related Questions