How to ignore favicon call in ASP.NET 5 Web API
Asked Answered
I

1

5

I'm practicing middlewares in ASP.NET Core 5. So I created a new web API project and removed all files except Startup.cs and Program.cs. I also removed all the service registration in ConfigureServices and removed all the middlewares in the Configure method.

I have added a simple inline Run middleware in the Configure method as shown below.

app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello from Run Middleware");
});

When I run and debug, I noticed that the above middleware is getting called twice. Later I figured out that second call is for favicon. When the web API is launched in browser, I noticed from the network tab that browser is making favicon request automatically and the confusing thing is that favicon request succeeds even though I don't have favicon in my project.

Screenshot: Network tab screen print

Here is the link to project repo.

Is it something like browser will by default make favicon call? or there is an option to ignore favicon call? When it comes to ignore, the call will be made by browser and we need to ignore the request in code? or we can prevent the favicon call itself?

Inconceivable answered 14/4, 2021 at 10:42 Comment(2)
You can check this thread,seems we can't prevent this:linkBeatty
try this line in the head section.: <link rel="icon" href="data:,">Logistics
R
6

Most browsers default to requesting a favicon whenever the user visits a new website.

There is no safe way to prevent this server-side; you could add a

<link rel="icon" href="https://some/random/path">

tag which tells the browser to look elsewhere, but even this is not guaranteed to work. Also you would need to serve a full HTML document.

The request succeeds since you don't handle that case in your app.Run function - it simply returns "Hello from Run Middleware", as for any other possible request path.

Note that you don't really need to care for that request: As soon as you add more logic to your app (e.g., controller routes), all calls to non-existing files will 404 automatically.


However, if you want to explicitly prevent the favicon requests from reaching your app.Run logic, you could add a middleware which detects the path and drops the request:

app.Use(async (context, next) =>
{
    if(context.Request.Path.Value == "/favicon.ico")
    {
        // Favicon request, return 404
        context.Response.StatusCode = StatusCodes.Status404NotFound;
        return;
    }
    
    // No favicon, call next middleware
    await next.Invoke();
});

app.Run(async (context) =>
{
    await context.Response.WriteAsync("Hello from Run Middleware");
});

As desired, the favicon request will fail now:

Screenshot of browser network debugger, showing status 200 for / and status 404 for favicon.ico

Rodenhouse answered 2/5, 2021 at 15:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.