如何排除ASP.NET Core API中的动词?
问题描述:
我需要排除允许用于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
的地方放什么?
答
在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返回任何HttpDelete
和HttpPut
的405
状态代码要求。