【问题标题】:Ignoring Request in middleware忽略中间件中的请求
【发布时间】:2017-11-08 08:39:04
【问题描述】:

所以我希望 IIS 在请求某些 url 时基本上不做任何事情,因为我想要从服务器端渲染到的反应路由器来处理请求。

用过这个link

我创建了一个检查每个请求的中间件。现在我不知道如何在找到正确的 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);
    }
}

【问题讨论】:

    标签: asp.net-core react-router-v4 reactjs.net


    【解决方案1】:

    如果您想停止请求,请不要调用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 文档,以更好地了解中间件的工作原理。

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

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

    但如果您想要服务器端渲染,请考虑使用微软的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" });
    });
    

    新模板还支持热模块更换

    【讨论】:

      猜你喜欢
      • 2016-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 2014-02-14
      • 2013-03-07
      • 1970-01-01
      相关资源
      最近更新 更多