2012-08-22 7 views
10

난 그냥 asp.net의 MVC 4 응용 프로그램과 내가 오류 브라우저에서 http://localhost:51416/api/get를 입력하지만 얻어서 방법 GET()를 호출하려고했던 그런WebApi 컨트롤러 메서드를 호출하는 방법?

public class UserApiController : ApiController 
{ 
    // GET api/default1 
    public IEnumerable<string> Get() 
    { 
     return new string[] { "value1", "value2" }; 
    } 

    // GET api/default1/5 
    public string Get(int id) 
    { 
     return "value"; 
    } 

    // POST api/default1 
    public void Post(string value) 
    { 
    } 

    // PUT api/default1/5 
    public void Put(int id, string value) 
    { 
    } 

    // DELETE api/default1/5 
    public void Delete(int id) 
    { 
    } 
} 

추가 기본 webapi 컨트롤러 만들었습니다

<Error> 
<Message> 
No HTTP resource was found that matches the request URI 'http://localhost:51416/api/get'. 
</Message> 
<MessageDetail> 
No type was found that matches the controller named 'get'. 
</MessageDetail> 
</Error> 

내 경로 설정 :

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

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

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

가 왜 기본적으로 작동하지 않습니다? 문제를 해결하려면 어떻게해야합니까?

답변

8

GET은 HTTP 동사 형식이기 때문에 URL에 get을 넣지 않아도됩니다.

기본적으로 브라우저는 URL을 입력하면 GET 요청을 보냅니다.

그래서 당신은 라우팅 설정에 경로를 지정할 때 당신은 "컨트롤러"접미사가 필요하지 않습니다

주 라인 defaults: new { controller = "UserApiController"...의 주석을 해제하면 기본 API를 컨트롤러 http://localhost:51416/api/

UserApiController 때문에 그것을 시도 defaults: new { controller = "UserApi", id = RouteParameter.Optional } )

또는 명시 적으로 제어 http://localhost:51416/api/userapi

을 지정해야합니다 그래서 올바른 dafaults 설정입니다

ASP.NET Web API site에서 Wep.API 및 HTTP 동사 기반 라우팅 규칙에 대해 알아볼 수 있습니다.

+0

'http : // localhost : 51416/api'가 생성되었습니다. 리소스를 찾을 수 없습니다. 'http : // localhost : 51416/api/userapi'가 작동합니다. 'http : // localhost : 51416/api' 경로를 고치는 방법? – Kuncevic

+0

default : new {controller = "UserApiController", id = RouteParameter.Optional}'기본값을 지정하기 때문에'http : // localhost : 51416/컨트롤러 – nemesv

+0

에 대한 컨트롤러가'defaults : new {controller = "UserApiController", id = RouteParameter.Optional}'와 연결되어 있었지만 여전히 리소스를 찾을 수 없습니다. 'localhost : 51416/api /' – Kuncevic

관련 문제