忽略中间件中的请求

Suj*_*ier 3 reactjs.net asp.net-core react-router-v4

所以我希望 IIS 在请求某些 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Tse*_*eng 5

如果您想停止请求,请不要调用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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

还要确保阅读ASP.NET Core 中间件文档,以便更好地了解中间件的工作原理。

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

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

但是,如果您想要服务器端渲染,请考虑使用 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" });
});
Run Code Online (Sandbox Code Playgroud)

新模板还支持热模块更换