aspnetcore添加方法过滤器,过滤掉没有被httpmethod特性标记的方法
时间: 2024-09-28 21:03:49 浏览: 28
在ASP.NET Core中,如果你想要过滤掉没有特定HTTP方法(如GET、POST等)标注的方法,你可以利用ActionFilterAttribute来实现自定义的方法过滤。首先,你需要创建一个新的Attribute继承自Microsoft.AspNetCore.Mvc.Filters.ActionFilterAttribute:
```csharp
using Microsoft.AspNetCore.Mvc.Filters;
public class HttpMethodOnlyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ActionDescriptor.MethodInfo.IsDefined(typeof(HttpMethodAttribute), true))
{
// 如果方法没有HttpMethodAttribute,抛出异常或返回405 Method Not Allowed
context.Result = new HttpStatusCodeResult(StatusCodes.Status405.MethodNotAllowed);
context.HttpContext.Response.ContentType = "text/plain";
context.Filters?.Invoke(context);
}
else
{
base.OnActionExecuting(context);
}
}
}
```
然后,在需要应用此过滤器的控制器上,通过`[AttributeUsage(AttributeTargets.Class)]`声明该过滤器:
```csharp
[AttributeUsage(AttributeTargets.Class)]
public class HttpMethodOnlyFilters : Attribute, IEndpointMetadataProvider
{
public void OnProvidersExecuted(IEndpointProvider endpointProvider)
{
endpointProvider.Endpoints
.Where(e => e.Metadata.Any(m => m is HttpMethodOnlyAttribute))
.ToList()
.ForEach(endpoint =>
{
endpoint.builder.Services.AddControllers(options =>
{
options.Filters.Add(typeof(HttpMethodOnlyAttribute));
});
});
}
public void OnEndpointsProvided(IEndpointBuilder builder)
{
}
}
```
现在,所有标注了`[HttpGet]`, `[HttpPost]`等HTTP方法特性的动作将被允许访问,而没有这些标注的方法会在尝试执行时返回405错误。
阅读全文