ASP.NET Core Web API:接受任何路由、任何方法、任何动词

huangapple go评论56阅读模式
英文:

ASP.NET Core Web API : accept any route, any method, any verb

问题

是的,这是可能的。

英文:

I need to create a mock service that accepts any route, any HTTP verb, etc..

[GET or POST or Whatever] http://[ip]/anyaction

Is it possible?

答案1

得分: 1

你可以创建自己的中间件,简单地回复所有请求:

public class AcceptAllMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {            
        context.Response.StatusCode = StatusCodes.Status200OK;
        await context.Response.WriteAsync("我接受任何请求。");            
        await context.Response.CompleteAsync();
    }
}

然后从Startup类中删除中间件管道中的所有内容,添加你的中间件:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMiddleware<AcceptAllMiddleware>();
}
英文:

You can create your own middleware that simply replies all requests:

public class AcceptAllMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {            
        context.Response.StatusCode = StatusCodes.Status200OK;
        await context.Response.WriteAsync(&quot;I accept anything and everything.&quot;);            
        await context.Response.CompleteAsync();
    }
}

Then remove everything from the middleware pipeline on the Startup class and add your middleware:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	app.UseMiddleware&lt;AcceptAllMiddleware&gt;();
}

huangapple
  • 本文由 发表于 2023年3月31日 02:11:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75891626.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定