2017-10-05 63 views
1

我需要排除允許用於API解決方案的動詞,但我找不到示例如何在web.config中執行此操作。如何排除ASP.NET Core API中的動詞?

我發現an example for MVC,看起來像這樣:

<configuration> 
<system.web> 
    <httpHandlers> 
    <remove verb="*" path="MyPage.aspx" type="MyHandler, MyAssembly"/> 
    <add verb="*" path="MyPage.aspx" type="MySpecialHandler, MyAssembly"/> 
    </httpHandlers> 
</system.web> 
</configuration> 

這是我應該怎麼做它的API呢?

如果是這樣,我應該在path的地方放什麼?

回答

2

在ASP.NET Core中,HTTP處理程序和模塊的實現被中間件所取代。本文有足夠的信息來說明如何從HTTP處理程序和模塊遷移到ASP.NET Core中間件。 https://docs.microsoft.com/en-us/aspnet/core/migration/http-modules

爲了從您的API實現HTTP動詞排斥,你可以寫一個簡單的中間件這樣的:

public class VerbsMiddleware{ 

     private readonly RequestDelegate _next; 
     private string[] VerbsToExclude = {"DELETE", "PUT"}; //You can put these in appsettings.json 

     public VerbsMiddleware(RequestDelegate next) 
     { 
      _next = next; 
     } 

     public async Task Invoke(HttpContext context){ 

      if (VerbsToExclude.Contains(context.Request.Method)) 
      { 
       context.Response.StatusCode = 405; 
       await context.Response.WriteAsync("Method Not Allowed"); 
      } 

      await _next.Invoke(context); 
     } 

    } 

通過上述中間件,您API返回任何HttpDeleteHttpPut405狀態代碼要求。

相關問題