Don’t you hate it when your Application Insights log is full of false 404 errors?
One of the easy requests to take care of is the one for Outlook Autodiscover. Here is a small and very efficient way to get rid of those in Optimizely CMS 12. Then you will have a fewer 404 errors to look at.
The reason we get 404 errors for POST /AutoDiscover/AutoDiscover.xml
(and similar variants) in the failed request log is that the Outlook application attempts to look up a configuration on start-up. And one of the ways to do this, is to search for the path on the domain of the active email address.
But a 404 error is never cached. So, Outlook will just try again next. After the 404 happened, it may have found its configuration another way. And yet next time it opens, it will try over again.
Solution
A simple solution is to simply redirect the request to the proper endpoint. With a small and lightweight middleware like the following we will see no more of these 404 errors in the logs.
namespace StefanOlsen.Web.Infrastructure.Middleware;
/// <summary>
/// Middleware to redirect autodiscover requests from Outlook to the external autodiscover service.
/// </summary>
public class AutodiscoverMiddleware
{
private static readonly PathString AutodiscoverPath = new("/autodiscover/autodiscover.xml");
// TODO: Amend redirect path with your own endpoint.
private static readonly StringValues RedirectLocation = new("http://autodiscover.yourdomain.tld/autodiscover/autodiscover.xml");
private readonly RequestDelegate _next;
public AutodiscoverMiddleware(RequestDelegate next) => _next = next;
public Task Invoke(HttpContext context)
{
if (!context.Request.Path.Equals(AutodiscoverPath))
{
return _next.Invoke(context);
}
context.Response.Headers.Location = RedirectLocation;
context.Response.StatusCode = (int)HttpStatusCode.PermanentRedirect;
return Task.CompletedTask;
}
}
Then we can call it from Startup.cs
like this.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<AutodiscoverMiddleware>();
// Other middlewares go here.
}
You should put it high up in the Configure method. Preferably higher up than authorization, HTTPS redirect and other middlewares. That way those autodiscover requests are handled before spending resources on running other middlewares.
Tip! This middleware pattern can also be used for other kinds of static redirect actions.