要在ASP.NET Core Web API中筛选GET方法,可以使用中间件或属性路由器来实现。下面是两个示例代码:
使用中间件:
public class FilterMiddleware
{
private readonly RequestDelegate _next;
public FilterMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Method == HttpMethod.Get.Method)
{
// perform filtering here
context.Response.StatusCode = StatusCodes.Status200OK;
await context.Response.WriteAsync("GET method is filtered");
}
else
{
await _next(context);
}
}
}
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware();
}
}
使用属性路由器:
public class ValuesController : ControllerBase
{
private List _values = new List() { "value1", "value2", "value3" };
[HttpGet("values")]
public ActionResult> Get(string filter)
{
if (!string.IsNullOrEmpty(filter))
{
return _values.Where(v => v.Contains(filter)).ToList();
}
else
{
return _values.ToList();
}
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
以上两个示例代码都可以实现GET方法的筛选,开发人员可以根据具体的需求来选择使用哪种方式。