Search code examples
asp.net-coreasp.net-core-2.2

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?


Solution

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