2014-12-17 6 views
0

ASP.NET 웹 API에서 컨트롤러를 만들었습니다. 다음은 컨트롤러 아래ASP.NET MVC 4의 WEB API에서 함수 가져 오기 요청 게시

public class CalculateController : ApiController 
{ 
    public IEnumerable<string> Get() 
    { 

     return new string[] { "from get method" }; 

    } 

    public IEnumerable<string> Post([FromBody]string value) 
    { 

     return new string[] { "from post method" }; 
    } 
} 

의 코드 내가 webAPI

HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://localhost:62479/api/calculate"); 

     StringBuilder postdata = new StringBuilder("value=Anshuman"); 
     byte[] data = Encoding.UTF8.GetBytes(postdata.ToString()); 
     httpWReq.Method = "POST"; 
     httpWReq.ContentType = "application/x-www-form-urlencoded"; 
     httpWReq.ContentLength = data.Length; 

     using (Stream stream = httpWReq.GetRequestStream()) 
     { 
      stream.Write(data, 0, data.Length); 
     } 
     HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse(); 
     string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); 
에 POST 요청을 만들기 위해 사용하고있는 코드입니다

문제는 내가 POST 요청을 할 경우에도 것입니다 그 경우에도 데이터는 컨트롤러의 GET 메소드에서 반환됩니다. Web API 프로젝트의 기본 구성을 변경하지 않았습니다. MVC 4를 사용 중입니다.

시간 내 주셔서 감사합니다. 다른 정보가 필요한 경우 의견을 추가하십시오.

동일한 컴퓨터에서 Visual Studio 2012로 실행되는 두 프로젝트가 있습니다.

+0

액션 이름 -http를 제공하는 명시 적으로 시도해보십시오 경로로 가져 오기 조치로 이동되는 게시물을 제한 할 관련 행동 속성 : // localhost를 : 62,479/api/calculate/Post – malkam

+0

@malkam이 작동하지 않습니다. 또한 기본 URL 경로 구성에는 URL에 작업 이름이 포함되지 않습니다. –

답변

3

매개 변수없이 게시 방법.

은 기본적으로는 다음과 같습니다 : 귀하의 경우

public void Post([FromBody]string value) 
{ 
    //do something with data you posted 
} 

을, 당신은 몇 가지 문자열 데이터를 반환하려는 경우 :

public IEnumerable<string> Post([FromBody]string value) 
{ 
    return new string[] { "from post method" }; 
} 

그냥 코드를 테스트했다. 그것은 잘 작동하고 게시 메서드를 올바르게 hitted. 하지만 제 경우에는 WebApiCOnfig.cs에서이 사실을 알게되었습니다. 웹 API 라우팅을보다 유연하게 만드는 데 도움이됩니다.

 config.Routes.MapHttpRoute(
      name: "DefaultApiWithId", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional }, 
      constraints: new { id = @"\d+" } 
     ); 

     config.Routes.MapHttpRoute(
      name: "DefaultApiWithAction", 
      routeTemplate: "api/{controller}/{action}" 
     ); 

     config.Routes.MapHttpRoute("DefaultApiGet", "api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }); 
     config.Routes.MapHttpRoute("DefaultApiPost", "api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) }); 
     config.Routes.MapHttpRoute("DefaultApiPut", "api/{controller}", new { action = "Put" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Put) }); 
     config.Routes.MapHttpRoute("DefaultApiDelete", "api/{controller}", new { action = "Delete" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Delete) }); 
+0

중요한 점은 POST가없는 POST 메서드가있는 이유입니다. – Rhumborl

+0

나는 변화를 만들었지 만 여전히 GET 방법을 쳤다. 변경 사항을 반영하도록 질문을 업데이트했습니다. –

+0

또한 웹 호스트 패키지를 으로 업그레이드해야했습니다.> Install-Package Microsoft.AspNet.WebApi.WebHost –

0

당신은 HttpPost를 추가 할 수 HttpGet 액션은

+0

이 중 하나가 작동하지 않습니다. –

관련 문제