2016-11-17 2 views
0

GET 메서드 만 항상 작동하지만 PUT, POST 및 DELETE에 대해서는 항상 오류가 발생합니다. 나는 IIS 사이트 에서뿐만 아니라 web.config를 통해 처리기 매핑을 업데이트하려고했습니다. 처음에는 상태 코드 405가 메소드 허용되지 않음으로 오류가 발생했습니다. (415), ReasonPhrase : 내가PUT, POST 및 DELETE RestAPI 오류

로 처리기 매핑을 변경하면

<system.webServer> 
    <handlers> 
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 
    <remove name="OPTIONSVerbHandler" /> 
    <remove name="TRACEVerbHandler" /> 
    <remove name="WebDAV" /> 
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> 

    <remove name="ExtensionlessUrl-Integrated-4.0" /> 
    <add name="ExtensionlessUrl-Integrated-4.0" 
     path="*." 
     verb="GET,HEAD,POST,DEBUG,DELETE,PUT" 
     type="System.Web.Handlers.TransferRequestHandler" 
     preCondition="integratedMode,runtimeVersionv4.0" /> 
</handlers> 

<validation validateIntegratedModeConfiguration="false" /> 

<modules> 
    <remove name="ApplicationInsightsWebTracking" /> 
    <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" /> 
    <remove name="WebDAVModule"/> 
</modules> 
는 "지원되지 않는 미디어 유형"로 (415)에 대한 오류를 받기 시작 .Following 내가

{상태 코드를 얻고있다 repsonce은 '지원되지 않는 미디어 유형 ', 버전 : 1.1, 내용 : System.Net.Http.StreamContent, 헤더 : { 캐시 제어 : no-cache Pragma : no-cache 서버 : Microsoft-IIS/8.5 X-AspNet- 버전 : 4.0 .30319 X-Powered-B y : ASP.NET 날짜 : 2016 년 11 월 17 일 16:44:52 GMT 콘텐츠 유형 : application/octet-stream; charset = utf-8 만료 : -1 콘텐츠 길이 : 100 }}

. 다음은 내 API 호출입니다

// PUT: api/CreditRequests/5 
    [ResponseType(typeof(void))] 
    public IHttpActionResult PutCreditRequest(Guid id, CreditRequest creditRequest) 
    { 
     if (!ModelState.IsValid) 
     { 
      return BadRequest(ModelState); 
     } 

     if (id != creditRequest.CreditRequestId) 
     { 
      return BadRequest(); 
     } 

     db.Entry(creditRequest).State = EntityState.Modified; 

     try 
     { 
      db.SaveChanges(); 
     } 
     catch (DbUpdateConcurrencyException) 
     { 
      if (!CreditRequestExists(id)) 
      { 
       return NotFound(); 
      } 
      else 
      { 
       throw; 
      } 
     } 

     return StatusCode(HttpStatusCode.NoContent); 
    } 

    // POST: api/CreditRequests 
    [ResponseType(typeof(CreditRequest))] 
    public IHttpActionResult PostCreditRequest(CreditRequest creditRequest) 
    { 
     if (!ModelState.IsValid) 
     { 
      return BadRequest(ModelState); 
     } 

     db.CreditRequests.Add(creditRequest); 

     try 
     { 
      db.SaveChanges(); 
     } 
     catch (DbUpdateException) 
     { 
      if (CreditRequestExists(creditRequest.CreditRequestId)) 
      { 
       return Conflict(); 
      } 
      else 
      { 
       throw; 
      } 
     } 

     return CreatedAtRoute("DefaultApi", new { id = creditRequest.CreditRequestId }, creditRequest); 
    } 

    // DELETE: api/CreditRequests/5 
    [ResponseType(typeof(CreditRequest))] 
    public IHttpActionResult DeleteCreditRequest(Guid id) 
    { 
     CreditRequest creditRequest = db.CreditRequests.Find(id); 
     if (creditRequest == null) 
     { 
      return NotFound(); 
     } 

     db.CreditRequests.Remove(creditRequest); 
     db.SaveChanges(); 

     return Ok(creditRequest); 
    } 

그리고 나는 HttpClient 객체를 사용하여 호출하고 있습니다. 코드로

string jsondata = JsonConvert.SerializeObject(item); 
      var content = new StringContent(jsondata, System.Text.Encoding.UTF8, "application/json"); 
      HttpResponseMessage response = null; 
      using (var client = GetFormattedHttpClient())// Adding basic authentication in HttpClientObject before using it. 
      { 
       if (IsNew == true) 
        response = client.PostAsync (_webUri, content).Result; 
       else if (IsNew == false) 
        response = client.PutAsync(_webUri, content).Result; 

      } 
      if (!response.IsSuccessStatusCode) 
           return false; 
      else 
      return true; 
+0

어디에서 사용 했습니까? [ResponseType (typeof (void))] –

+0

DB에 레코드를 추가하기위한 POST 메서드를 먼저 테스트하고 있습니다. PUT의 경우 StatusCode를 NoContent로 가져 오는 데 초점을 맞추고 있습니다 –

+0

해당 특성을 제거하십시오. 필요하지 않습니다. – Amy

답변

0

이 작품은 나를 위해 작동합니다.

protected async Task<String> connect(String URL,WSMethod method,StringContent body) 
{ 
     try 
     { 

      HttpClient client = new HttpClient 
      { 
       Timeout = TimeSpan.FromSeconds(Variables.SERVERWAITINGTIME) 
      }; 
      if (await controller.getIsInternetAccessAvailable()) 
      { 
       if (Variables.CURRENTUSER != null) 
       { 
        var authData = String.Format("{0}:{1}:{2}", Variables.CURRENTUSER.Login, Variables.CURRENTUSER.Mdp, Variables.TOKEN); 
        var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData)); 

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue); 
       } 

       HttpResponseMessage response = null; 
       if (method == WSMethod.PUT) 
        response = await client.PutAsync(URL, body); 
       else if (method == WSMethod.POST) 
        response = await client.PostAsync(URL, body); 
       else 
        response = await client.GetAsync(URL); 

       .... 
} 
관련 문제