If you use the current UseStatusCodePages middleware, it's going to affect every single error. In order to accomplish what you're looking for, you need to create your own Middleware, that needs to be placed right after your default error handling middleware:
//Startup.cs
public void Configure(IApplicationBuilder app)
{
app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");
app.UseImageNotFoundMiddlewareWithRedirect("/Home/ImageError");
}
This should get you started: Github - StatusCodePage
Here's an example middleware to simulate maybe what you're looking for:
public class ImageNotFoundMiddleware
{
private readonly RequestDelegate _next;
private readonly StatusCodePagesOptions _options;
public ImageNotFoundMiddleware(RequestDelegate next, IOptions<StatusCodePagesOptions> options)
{
_next = next;
_options = options.Value;
if (_options.HandleAsync == null)
{
throw new ArgumentException("Missing options.HandleAsync implementation.");
}
}
public async Task Invoke(HttpContext context)
{
var statusCodeFeature = new StatusCodePagesFeature();
context.Features.Set<IStatusCodePagesFeature>(statusCodeFeature);
await _next(context);
if (!statusCodeFeature.Enabled)
{
// Check if the feature is still available because other middleware (such as a web API written in MVC) could
// have disabled the feature to prevent HTML status code responses from showing up to an API client.
return;
}
// Do nothing if a response body has already been provided or not 404 response
if (context.Response.HasStarted
|| context.Response.StatusCode != 404
|| context.Response.ContentLength.HasValue
|| !string.IsNullOrEmpty(context.Response.ContentType))
{
return;
}
// todo => Here is where you'd also add your logic to check for the image 404...
if (context.Request.Path.Value.EndsWith(".JPG", StringComparison.OrdinalIgnoreCase)
|| context.Request.Path.Value.EndsWith(".PNG", StringComparison.OrdinalIgnoreCase)
|| context.Request.Path.Value.EndsWith(".GIF", StringComparison.OrdinalIgnoreCase)
)
{
var statusCodeContext = new StatusCodeContext(context, _options, _next);
await _options.HandleAsync(statusCodeContext);
}
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class ImageNotFoundMiddlewareExtensions
{
public static IApplicationBuilder UseImageNotFoundMiddlewareWithRedirect(this IApplicationBuilder app,
string locationFormat)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return app.UseMiddleware<ImageNotFoundMiddleware>(
Options.Create(
new StatusCodePagesOptions
{
HandleAsync = context =>
{
var location = string.Format(
CultureInfo.InvariantCulture,
locationFormat.StartsWith("~") ? locationFormat.Substring(1) : locationFormat,
context.HttpContext.Response.StatusCode);
context.HttpContext.Response.Redirect(
locationFormat.StartsWith("~")
? context.HttpContext.Request.PathBase + location
: location);
return Task.FromResult(0);
}
}
)
);
}
}