.net core action filters RRS feed

  • Question

  • User-357141231 posted

    Hi Guys.

    I am trying to display an image in raw using an action filter. I did this a long time ago using filters in IIS and .net pages because I wanted to display an image but execute other code behind the scenes, such as entity framework etc.

    Can someone give me an example of how I would do this in .net core mvc?

    I'm also trying to work out the quickest way to do this. I noticed when I did this years ago, some larger images took a long time to display.

    My old image handler was as follows. It's pretty horrible and I don't want to repeat it.

    public void ProcessRequest(System.Web.HttpContext contex)
            HttpResponse response = contex.Response;
            HttpRequest request = contex.Request;
            // set imagePath to the physical path of the request
            string imagePath = request.PhysicalPath;
            // if file is disabled, abort
            string fileName = Path.GetFileName(request.FilePath);
            // image enabled by default
            bool enabledResult = true;
            // now we want to check if the file actually exists before displaying it to the user
            // in future it would be less expensive to check a database
            if (File.Exists(imagePath))
                   // only increment images from \images\
                    if (imagePath.Contains(@"\images\"))
                        // open db connection and increment a hit
                        string connectionString = WebConfigurationManager.ConnectionStrings["ImageShop"].ConnectionString;
                        SqlConnection con = new SqlConnection(connectionString);
                        // following used to check if image is enabled
                        string selectQuery = @"SELECT Enabled FROM Image where (ImageName = @ImageName)";
                        SqlCommand sqlcommand = new SqlCommand(selectQuery, con);
                        sqlcommand.Parameters.Add("@ImageName", System.Data.SqlDbType.VarChar, 50).Value = fileName;
                        // required for the later function that checks to see if the image is enabled.
                        enabledResult = (bool)sqlcommand.ExecuteScalar();
                        // try incrementing the current image in db
                            FileInfo finfo = new FileInfo(imagePath);
                            // add a hit for the current image
                            string query = @"INSERT INTO dbo.ImageHits
                                    (ImageName, ImageSize, CreateDate) VALUES
                                    (@Image, @ImageSize, GETDATE())";
                            SqlCommand sqlcommand2 = new SqlCommand(query, con);
                            sqlcommand2.Parameters.Add("@Image", System.Data.SqlDbType.VarChar, 50).Value = fileName;
                            sqlcommand2.Parameters.Add("@ImageSize", System.Data.SqlDbType.Int).Value = (int)finfo.Length;
                            // error
                    // probably don't need to do this, better safe than sorry
                    string extension = Path.GetExtension(imagePath).ToLower();
                    switch (extension)
                        case ".jpg":
                            response.ContentType = "image/jpeg";
                        case ".jpeg":
                            response.ContentType = "image/jpeg";
                        case ".gif":
                            response.ContentType = "image/gif";
                        case ".bmp":
                            response.ContentType = "image/bmp";
                        case ".png":
                            response.ContentType = "image/png";
                    // display image
                    // will be null if not from database.
                    if (enabledResult)

    Monday, June 1, 2020 1:56 AM

All replies

  • User1686398519 posted

    Hi,  infused

    Depends on what you want, I think it is possible to write the relevant code directly in the controller and combine it with the EF framework. I made an example, you can refer to it.

    Remarks: I write the name and type of the picture on the page for testing, you can modify it according to your needs.


    public class ShowImgeController : Controller
            private theManagerContext _db; 
            private readonly IWebHostEnvironment _host;
            public ShowImgeController(theManagerContext context, IWebHostEnvironment host)
                this._db = context; 
                this._host = host;
            public IActionResult DisplayImage()
                return View();
            public IActionResult DisplayImage(string ImageName,string ContentType)
                var image=_db.Images.Where(i => i.ImageName == ImageName).SingleOrDefault();
                if (image != null)
                    string contentRootPath = _host.ContentRootPath;
                    var virtualpath = Path.Combine(contentRootPath, @"\images\" + ImageName+"."+ContentType);
                    var path = contentRootPath + @"\wwwroot\images\" + ImageName + "." + ContentType;
                    if (System.IO.File.Exists(path))
                        return File(virtualpath, "image/"+ContentType);
                return View();


    @using (Html.BeginForm())
           <input name= "ImageName" value="Test1"/>
           <input name = "ContentType" value= "png" />
    <button type="submit">SUBMIT</button>

    Here is the result.

    Best Regards,


    Monday, June 1, 2020 12:40 PM