中间件忽略请求

6
我希望IIS在请求某些URL时基本上不做任何事情,因为我想让React Router(我已经从服务器端呈现)处理请求。
使用此链接 我创建了一个中间件来检查每个请求。现在我不知道如何忽略或中止一旦找到正确的URL就停止这个请求。
public class IgnoreRouteMiddleware
{

    private readonly RequestDelegate next;

    // You can inject a dependency here that gives you access
    // to your ignored route configuration.
    public IgnoreRouteMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.Path.HasValue &&
            context.Request.Path.Value!="/")
        {


           // cant stop anything here. Want to abort to ignore this request

        }

        await next.Invoke(context);
    }
}
1个回答

8
如果你想停止一个请求,只需要不调用next.Invoke(context),因为这会调用管道中的下一个中间件。不调用它,就会结束请求(并且在它的next.Invoke(context)之后的前一个中间件代码将被处理)。
在你的情况下,只需将调用移动到else分支或否定if表达式即可。
public class IgnoreRouteMiddleware
{

    private readonly RequestDelegate next;

    // You can inject a dependency here that gives you access
    // to your ignored route configuration.
    public IgnoreRouteMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (!(context.Request.Path.HasValue && context.Request.Path.Value!="/"))
        {
            await next.Invoke(context);
        }
    }
}

同时,确保阅读ASP.NET Core Middleware文档,以更好地理解中间件的工作原理。

中间件是组装到应用程序管道中以处理请求和响应的软件。每个组件:

  • 选择是否将请求传递到管道中的下一个组件。
  • 可以在调用管道中的下一个组件之前和之后执行工作。

但如果您想要服务器端呈现,请考虑使用 Microsoft 的JavaScript/SpaServices库,它已经内置在较新的模板(ASP.NET Core 2.0.x)中,并注册回退路由如下。

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");

    routes.MapSpaFallbackRoute(
        name: "spa-fallback",
        defaults: new { controller = "Home", action = "Index" });
});

新模板还支持热模块替换。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接