如何排除 ASP.NET 核心 API 中的动词?
How do I exclude verbs in ASP.NET Core API?
我需要排除 API 解决方案允许的动词,但我无法在 web.config
中找到如何执行此操作的示例。
我发现 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 核心中,HTTP 处理程序和模块的实现被中间件取代。本文包含有关如何从 HTTP 处理程序和模块迁移到 ASP.NET 核心中间件的足够信息。
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);
}
}
使用上述中间件,对于任何 HttpDelete
和 HttpPut
请求,您 API returns 状态码 405
。
我需要排除 API 解决方案允许的动词,但我无法在 web.config
中找到如何执行此操作的示例。
我发现 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 核心中,HTTP 处理程序和模块的实现被中间件取代。本文包含有关如何从 HTTP 处理程序和模块迁移到 ASP.NET 核心中间件的足够信息。 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);
}
}
使用上述中间件,对于任何 HttpDelete
和 HttpPut
请求,您 API returns 状态码 405
。