Ignoring Request in middleware
Asked Answered
D

1

6

So I want IIS to basically not do anything when certain urls are requested bacause I want react router to which I have rendered from serverside, to handle the request.

Used this link

I have created a middleware that checks each request. Now i dont know how to ignore or abort this request once I find the right urls.

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);
    }
}
Dissemblance answered 8/11, 2017 at 8:39 Comment(0)
O
8

If you want to stop a request, just don't call next.Invoke(context), because this will call the next middleware in the pipeline. Not calling it, just ends the request (and the previous middlewares code after it's next.Invoke(context) will be processed).

In your case, just move the call to the else branch or just negate the if expression

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);
        }
    }
}

Also make sure to read the ASP.NET Core Middleware documentation for a better understanding on how middlewares work.

Middleware is software that is assembled into an application pipeline to handle requests and responses. Each component:

  • Chooses whether to pass the request to the next component in the pipeline.
  • Can perform work before and after the next component in the pipeline is invoked.

But if you want server-sided rendering, consider using Microsoft`s JavaScript/SpaServices library, which is already built in in the newer templates (ASP.NET Core 2.0.x) and register a fallback route such as.

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

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

The new templates also come with support for hot module replacement

Olander answered 8/11, 2017 at 9:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.