受欢迎的博客标签

Set default images when image is not found Middleware in Asp .Net Core

Published

1、 Using the code  The Middelware

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using System.Diagnostics;
using Microsoft.AspNetCore.Builder;



namespace Nop.Web.Framework.Middleware
{

    /// <summary>
    /// How to set default images when image is not found in ASP.NET Core
    /// https://code.msdn.microsoft.com/How-to-set-default-image-15c3bd56#content
    /// </summary>
    public class DefaultImageMiddleware
    {
        private readonly RequestDelegate _next;

        public static string DefaultImagePath { get; set; }

        public DefaultImageMiddleware(RequestDelegate next)
        {
            this._next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            await _next(context);
            if (context.Response.StatusCode == 404)
            {
                var contentType = context.Request.Headers["accept"].ToString().ToLower();
                if (contentType.StartsWith("image"))
                {
                    await SetDefaultImage(context);
                }
            }
        }

        private async Task SetDefaultImage(HttpContext context)
        {
            try
            {
                string path = Path.Combine(Directory.GetCurrentDirectory(), DefaultImagePath);

                FileStream fs = File.OpenRead(path);
                byte[] bytes = new byte[fs.Length];
                await fs.ReadAsync(bytes, 0, bytes.Length);
                //this header is use for browser cache, format like: "Mon, 15 May 2017 07:03:37 GMT". 
                context.Response.Headers.Append("Last-Modified", $"{File.GetLastWriteTimeUtc(path).ToString("ddd, dd MMM yyyy HH:mm:ss")} GMT");

                await context.Response.Body.WriteAsync(bytes, 0, bytes.Length);
            }
            catch (Exception ex)
            {
                await context.Response.WriteAsync(ex.Message);
            }
        }
    }

    public static class DefaultImageMiddlewareExtensions
    {
        public static IApplicationBuilder UseDefaultImage(this IApplicationBuilder app, string defaultImagePath)
        {
            DefaultImageMiddleware.DefaultImagePath = defaultImagePath;

            return app.UseMiddleware<DefaultImageMiddleware>();
        }
    }


}

2、Startup.cs/Configure method

public void Configure(IApplicationBuilder app)         

 {             

   app.UseDefaultImage(defaultImagePath: Configuration.GetSection("defaultImagePath").Value);                  app.UseMvcWithDefaultRoute();         

 

 }

3、Appsettings.json

{   

 "defaultImagePath": "wwwroot\\DefaultImage.png" 

} .