2017-05-09 12 views
0

Ich möchte Ruhe API erstellen, aber ich habe Probleme mit dem Routing. Diese URL ist ok: localhost/project/controller/action/id, aber ich möchte diese URL localhost/project/controller/id auch. Zum Beispiel: localhost/project/article/5: ArticleController.Get(int id) Dies ist mein Code: ProjektcontrollerASP MVC Routing Rest api

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

Strecke 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 } 
      ); 
     } 

Wenn ich URL localhost/Projekt aufrufen/article/5, Fehlermeldung A Öffentlichkeit Die Aktionsmethode '5' wurde nicht im Controller 'ArticleController' gefunden.

Wo ist das Problem? verwenden Dank

+0

Welche Version von mvc Sie verwenden? – Jamiec

Antwort

1

können Sie attribute routing

Beispiel:

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

ODER

Default Route Table

Beispiel:

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 } 
      ); 

     } 

wie pro Ihre Anforderung, Ihr Routing ist:

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

ODER

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

Danke, aber das funktioniert nicht richtig. Ich brauche map url localhost/project/article/5 zu ArticleController.Get (int id) – bluray

+0

Es tut mir leid, es funktioniert nicht richtig. Fehlermeldung ist eine öffentliche Aktion-Methode '5' gefunden wurde, nicht auf Controller – bluray

+0

ich einfaches Beispiel ApiController erstellt: ' [HttpGet] [Weg ("api/example")] public void Get (int id) { } 'Wenn ich Url api/example/1 rufe 404 – bluray