Yoda
Yoda

Reputation: 18068

How to raise HTTP404 on certain suffix in URL?

I'd like to raise HTTP404 Not Found when url is terminated by /, example www.abc.com/hubbahubba/. I don't know if it should be defined in routing or should it be done by middleware?

I was thinking about doing it this way:

routes.MapRoute( _
      name:="CatchTrailingSlash", 
      url:="*+/", 
      defaults:=New With {.controller = "Error", .action = "Handler"} 
  )

but this would mean that I need to create dedicated controller for it. What is the correct approach?

Upvotes: 0

Views: 35

Answers (1)

Nan Yu
Nan Yu

Reputation: 27578

You can use Middleware :

app.Use(async (context, next) =>
    {
        if (context.Request.GetDisplayUrl().EndsWith("/"))
        {
            context.Response.StatusCode = StatusCodes.Status404NotFound;
            return;
        }

        await next.Invoke();

    });

or use Action filter :

using Microsoft.AspNetCore.Http.Extensions;

public class GlobalFilter: IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        var result = context.HttpContext.Request.GetDisplayUrl().EndsWith("/");
        if (result)
        {
            context.Result = new NotFoundResult();
            return;
        }

    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
    }
}

Register globally :

services.AddMvc(config =>
    {
        config.Filters.Add(new GlobalFilter());
    }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

Upvotes: 1

Related Questions