Search code examples
routesservicestackfaviconignoreroute

ServiceStack 4: Ignore favicon.ico in Fallback Route


I have a more or less static website build on ServiceStack.Razor, with the routes defined as the following patterns: I am trying to ignore favicon.ico, but route the paths like "/" or "/en-us" to the HomeScenario. Other sample routes are /{Lang}/cook or /{Lang}/cheer, etc.

Unfortunately, my current approach is not ignoring favicon.ico. I would like to implement this without hopefully writing a lot of extra code.

[FallbackRoute("/{Lang*}")]
public class HomeScenario : LocalizedRequest
{

}

public class LocalizedRequest
{
    public LocalizedRequest()
    {
        Lang = "en-us";
    }
    public string Lang { get; set; }
}

Here is the default request

[DefaultView("home")]
public object Get(HomeScenario request)
{
    var cacheKey = GetCacheKey ("home", request.Lang);
    return base.Request.ToOptimizedResultUsingCache (base.Cache, cacheKey, () => {
        var response = LoadJson<HomeScenarioResponse> (request.Lang, "home");
        return response;
    });
}

Solution

  • You can just ignore requests in code:

    [DefaultView("home")]
    public object Get(HomeScenario request)
    {
        if (base.Request.PathInfo == "/favicon.ico")
            return HttpError.NotFound(request.PathInfo);
    
        var cacheKey = GetCacheKey ("home", request.Lang);
        return base.Request.ToOptimizedResultUsingCache (base.Cache, cacheKey, () => {
            var response = LoadJson<HomeScenarioResponse> (request.Lang, "home");
            return response;
        });
    }
    

    Otherwise you can register a CatchAll handler further up the Request Pipeline that handles unwanted requests, e.g:

    this.CatchAllHandlers.Add((httpmethod, pathInfo, filepath) => {
    
        if (pathInfo == "/favicon.ico") 
            return new NotFoundHttpHandler();
    
        return null; //continue processing request
    });