2017-10-10 23 views
0

私はASP.NET/C#でAPIを構築しています。 PUTのいずれかを作るか、または要求を削除しようとするときしかし、私は次のエラーが表示されます。私は、この問題は以前に議論されているASP.NET Web API "要求されたリソースがhttpメソッドのPUT/DELETEをサポートしていません"

"The requested resource does not support http method PUT (or DELETE)" 

実現します。しかし、私は関連する質問に対する回答(this oneを含む)を見てきましたが、解決策をまだ見つけていません。 WebDAVを無効にし、その動詞がExtensionlessUrlHanlderで許可されていることを確認しました。次のように私のweb.configファイルの「Webサーバ」の部分は次のとおりです。

<system.webServer> 
    <modules> 
     <remove name="FormsAuthentication" /> 
     <remove name="WebDAVModule"/> 
     <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" /> 
     <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" /> 
     <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" /> 
    </modules> 
    <httpProtocol> 
     <customHeaders> 
     <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> 
     </customHeaders> 
    </httpProtocol> 
    <handlers> 
     <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 
     <remove name="OPTIONSVerbHandler" /> 
     <remove name="WebDAV" /> 
     <remove name="TRACEVerbHandler" /> 
     <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> 
    </handlers> 
    <validation validateIntegratedModeConfiguration="false" /> 
</system.webServer> 

次のようにコントローラは、次のとおりです。

namespace MidamAPI.Controllers 
{ 
    [RoutePrefix("SupplyItems")] 
    public class SupplyItemsController : ApiController 
    { 
     UnitOfWork worker = new UnitOfWork(); 

     [Route("")] 
     [HttpGet] 
     public string Get() 
     { 
      IEnumerable<SupplyItemsDTO> dtoList = Mapper.Map<List<SupplyItem>, List<SupplyItemsDTO>>(worker.SupplyItemRepo.Get().ToList()); 
      return JsonConvert.SerializeObject(dtoList); 
     } 

     [Route("{propertyType}")] 
     public string Get(String propertyType = "BK") 
     { 
       IEnumerable<SupplyItemsDTO> dtoList = null; 
      if (propertyType.Equals("POPEYES", StringComparison.CurrentCultureIgnoreCase)) 
      {dtoList = Mapper.Map<List<PopeyesSupplyItem>, List<SupplyItemsDTO>>(worker.PopeyesItemRepo.Get().ToList()); 

      } 
      dtoList = Mapper.Map<List<BKSupplyItem>, List<SupplyItemsDTO>>(worker.BKItemRepo.Get().ToList()); 


      return JsonConvert.SerializeObject(dtoList); 
     } 

     [Route("{id:int}")] 
     public string Get(int id) 
     { 
      SupplyItemsDTO dto = Mapper.Map<SupplyItem, SupplyItemsDTO>(worker.SupplyItemRepo.GetByID(id)); 

      return JsonConvert.SerializeObject(dto); 
     } 

      [Route("")] 
      [HttpPost] 
     public HttpResponseMessage Post([FromBody]SupplyItem itm) 
     { 
      try 
      { 
       worker.SupplyItemRepo.Insert(itm); 
       worker.Save(); 
       return Request.CreateResponse(HttpStatusCode.OK, itm); 
      } 
      catch (Exception ex) 
      { 
       return Request.CreateResponse(HttpStatusCode.BadRequest, ex); 
      } 

     } 

       [Route("")] 
      [HttpDelete] 
      public HttpResponseMessage Delete(int id) 
      { 
       try 
       { 
        SupplyItem itm = worker.SupplyItemRepo.GetByID(id); 
        worker.SupplyItemRepo.Delete(itm); 
        worker.Save(); 
        return Request.CreateResponse(HttpStatusCode.OK, itm); 
       } 
       catch(Exception ex) 
       { 
        return Request.CreateResponse(HttpStatusCode.BadRequest, ex); 
       } 
      } 

     [Route("")] 
     [HttpPut] 
     public HttpResponseMessage Put(int id, SupplyItem item) { 
      try 
      { 
       item.ID = id; 
       worker.SupplyItemRepo.Update(item); 
       return Request.CreateResponse(HttpStatusCode.OK, item); 
      } 
      catch(Exception ex) 
      { 
       return Request.CreateResponse(HttpStatusCode.BadRequest, ex); 
      } 
     } 
    } 
} 

予想通りGETとPOSTが作業を呼び出します。私はapplicationhost.configファイルを変更したくない、実際には(これは私の開発マシンであるため)いかなる方法でもWebサーバーを変更するか、セキュリティの脆弱性を表す可能性のあるヘッダーを使用します。

レスポンスヘッダ:IISログの

Access-Control-Allow-Credentials →true 
Access-Control-Allow-Headers →Origin, X-Requested-With, Content-Type, Accept, X-Token,Authorization 
Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS 
Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS 
Access-Control-Allow-Origin →* 
Allow →GET 
Cache-Control →no-cache 
Content-Length →72 
Content-Type →application/json; charset=utf-8 
Date →Tue, 10 Oct 2017 13:39:03 GMT 
Expires →-1 
Pragma →no-cache 
Server →Microsoft-IIS/8.0 
X-AspNet-Version →4.0.30319 
X-Powered-By →ASP.NET 
X-SourceFiles →=?UTF-8?B?QzpcVmlzdWFsIFN0dWRpbyBQcm9qZWN0c1xNaWRhbWVyaWNhQVBJXE1pZGFtQVBJXHN1cHBseWl0ZW1zXDQ1NA==?= 

要求:

2017-10-10 13:27:35 ::1 PUT /supplyitems/454 - 57263 - ::1 PostmanRuntime/6.3.2 - 405 0 0 0 

私のルーティング:何かアドバイスが高く評価され

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

。私はIIS Expressを使用しています。ありがとう。

+1

あなたはCORSについて読むべきです。このGoogleプラグインをインストールした後も問題が解決しない場合は、試してみてください。 https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=ja。それが可能な場合は、アプリケーションでCORSの適切な構成を設定する必要があることを意味します。それが役に立てば幸い! –

答えて

1

あなたはまだいくつかの余分なモジュールがインストールされている場合があります。それらを修正しても、リクエストとルートは一致しません。

ルート属性を使用して明示的にルートを設定したため、ルート設定は無視されます。 DELETEメソッドのルート属性を[Route("{id:int}")]に更新する必要があります。 PUTメソッドについては、あなたがやっていることについて少しはっきりしていませんが、私はこのようなことをしたいと思うでしょう: [Route("{id:int}")] [HttpPut] public HttpResponseMessage Put([FromUrl]int id, [FromBody]SupplyItem item) { ...

+0

私の場合、これは答えになりました。[Route( "{id:int}")]をPUTメソッドとDELETEメソッドに置くことで修正されました。すべての回答をありがとう。私のことはまったく間違っているようになりました。 – KellyMarchewa

0

私のためにそのエラーと冒険をした

あなたはいくつかの余分なIISモジュールがインストールされているせいか、ということになっている:あなたがそれを必要としない場合は WebDAVを私はちょうどあなたのIISから削除します。

このモジュールは、IISロールの一部です。 それを取り除くには Windowsの機能 - > Windowsの機能のオン/オフ - >インターネットインフォメーションサービス - >ワールドワイドウェブサービス - >一般的なHTTPの機能 - > WebDAVの公開。

これを維持したい場合は、私が思っているISAPIフィルタにPUT/DELETEを追加する必要があります。

もっとここについての説明:https://stackoverflow.com/a/33552821/4869329

関連する問題