1

이 같은 URL을 사용하여 표현 할 수있는 요청 제공하기 위해 작성해야 결과를 ASP.NET MVC4 및 웹 API를 사용하는 고객 API를 만드는 방법 :미리 정의 된 JSON은 ASP.NEt MVC4 응용 프로그램 JSON 웹 API의

  1. http://localhost:52216/erp/api/customers 반환 모든 고객

    같은 "소프트"가 포함되어 고객의
  2. http://localhost:52216/erp/api/customers?term=soft 반환 목록입니다. 자동 완성에 사용됩니다. 이러한 요청에서

결과는 하나의 속성, 발견 고객의 배열을 포함하는 고객을 포함 JSON 객체 여야합니다.

3. 포스트 요청에 http://localhost:52216/erp/api/customers 은 하나의 속성이 포함 된 JSON 객체, 일부 속성 변경으로 고객 저장된 포함 고객해야이 방법에서 JSON

결과로 요청 본문에 지정되어 새로운 고객을 추가해야합니다 .

아래의 API 컨트롤러에서 사용하려고합니다.

<Error><Message>No HTTP resource was found that matches the request URI 'http://localhost:52216/erp/api/customers'.</Message> 
<MessageDetail>No action was found on the controller 'Customers' that matches the request.</MessageDetail> 
</Error> 

XML 형식으로 입력하면 브라우저 http://localhost:52216/erp/api/customers 반환 오류가 어떻게이 문제를 해결하려면? 그런 요청에 대한 크리 테 API 클래스의 올바른 방법은 무엇입니까?

요청 데이터 형식을 변경할 수 없습니다. 클래스 메서드 이름을 변경하고 필요에 따라 다른 이름을 가진 메서드를 별도로 만들 수 있습니다.

using Erp.Models; 
using System.Web.Http; 

namespace Erp.Controllers 
{ 
    [Authorize] 
    public class CustomersController : ApiController 
    { 
     public object Get(string term) 
     { 
      Customer[] res = CustomerRepository.GetAllOrForTerm(term); 
      return new { customers = res }; 
     } 

     public object Post([FromBody]Customer customer) 
     { 
      Customer res = CustomerRepository.Save(customer); 
      return new { customer = res }; 
     } 
    } 
} 

기본 라우팅이 사용됩니다

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

업데이트

응용 프로그램이 그렇게 도움이되지 않습니다 제거 ERP 가상 디렉터리에서 실행 중입니다.

나는 브라우저도 시도

http://localhost:52216/erp/api/customers/get 

http://localhost:52216/erp/api/customers/Get 

하지만 다음 컨트롤러가 기본 경로 구성에서 잘 작동합니다 오류

<Error> 
<Message> 
No HTTP resource was found that matches the request URI 'http://localhost:52216/erp/api/customers/get'. 
</Message> 
<MessageDetail> 
No action was found on the controller 'Customers' that matches the request. 
</MessageDetail> 
</Error> 
+0

FromBody는 무엇을합니까? 당신이 제공 한 동작 매개 변수는 경로 설정에서 필수 항목입니다 –

+2

** http : // localhost : 52216/erp/api/customers에서 ** "erp /"** 부분을 삭제하려고합니다 –

+0

@Vishal Sharma : FromBody는 POST 메시지 본문입니다. 추가 조치를 시도했지만 문제가 지속됩니다. 응용 프로그램은 웹용 VS2013 Express의 ERP 가상 디렉터리에서 실행됩니다. erp가 제거되면 iis에서 404.0 오류가 반환됩니다. 나는 질문을 업데이트했다. – Andrus

답변

2

을 가지고 :

public class CustomersController : ApiController 
{ 
    // This will match GET /api/customers 
    public HttpResponseMessage Get() 
    { 
     Customer[] res = CustomerRepository.GetAllCustomers(); 
     return Request.CreateResponse(HttpStatusCode.OK, result); 
    } 

    // This will match GET /api/customers?term=foo_bar 
    public HttpResponseMessage Get(string term) 
    { 
     Customer[] res = CustomerRepository.GetAllOrForTerm(term); 
     return Request.CreateResponse(HttpStatusCode.OK, res); 
    } 

    // This should match POST /api/customers 
    public HttpResponseMessage Post(Customer customer) 
    { 
     ... 
     return Request.CreateResponse(HttpStatusCode.Created, customer); 
    } 
} 

코드에서 [Authorize] 속성을 사용하여 CustomersController을 장식 한 것으로 보이며 사용중인 인증 메커니즘의 종류를 실제로 설명하지 않아도됩니다. 그러나 승인을 사용하는 경우 유효한 자격 증명을 요청과 함께 제공해야합니다.

웹 API 대신에 ServiceStack을 확인하십시오. .NET에서 RESTful 웹 서비스를 작성하는 것이 얼마나 쉬운가에 매료 될 것이다. Web API v2에서는 속성 기반 라우팅 (라우팅 단순화)을 도입하여 ServiceStack에 한발 더 다가 갔지만 메시지 기반 서비스를 만드는 또 다른 단계가 있습니다. 그러면 웹 API가 실제로 유용 할 것입니다. 이 마지막 단계를 마칠 때까지 개인적으로 RESTfule 서비스를 작성하는 데 필요한 단순성을 제공하는 ServiceStack을 계속 사용하겠습니다.

+0

감사합니다. CreateResponse를 사용하는 이유는 무엇입니까? 이렇게하려면 추가 dll을 참조해야합니다. VS2013 웹 API 템플릿과 내가 찾은 모든 샘플은 단순히 내 질문에 코드와 같은 객체를 반환합니까? – Andrus

+0

CreateResponse를 사용하고 있습니다. IMHO는 웹 API에서 응답을 반환하는 올바른 방법입니다. 그리고 아니요, 추가 DLL을 참조 할 필요가 없습니다. Request.CreateResponse 메소드는 코어의 일부입니다. 컨트롤러 액션은'HttpResponseMessage' 인스턴스를 반환해야합니다. 올바른 상태 코드와 내용 유형을 지정할 수 있습니다. –

+0

양식 승인을 사용 중이며 브라우저가 적절한 쿠키를 전달합니다. 이것은 json이 반환 한 메소드를 응답으로 옮기는 기존 mvc4 Mono 어플리케이션에 추가 된 첫 번째 API입니다.이 메소드는 HTML 뷰를 응답으로 반환합니다. 응용 프로그램이 Windows 2003 서버 및 Mono에서도 실행되어야하므로 Web API v2로 이동할 수 없습니다. Servicestack으로 이사하는 것이 합리적입니까? – Andrus