Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not allowed to load local resource: file:// in ASP.NET Core

I have images saved on my C drive as follows:

C:\Users\Public\images\employees

I have a view model in my project that contains a property string ImageUrl. In my Controller, I am fetching the image according to the image name:

var model = new EmployeeViewModel
{
    FirstName = employeeDetails.FirstName,
    FullName = employeeDetails.FullName,
    LastName = employeeDetails.LastName,
    ImageUrl = new System.Uri(Path.Combine(@"C:\Users\Public\images\employees", "John.jpg")).AbsoluteUri
};

Then I am passing this model into the View. In my View, I want to display the image as follows:

But I am getting an exception

Not allowed to load local resource: file:// in ASP.NET Core

Can someone please help with this. Also, my application will de deployed to a domain. How can I ensure the image will still display?

like image 478
crazydev Avatar asked Sep 02 '25 10:09

crazydev


1 Answers

passing this model into the View. In my View, I want to display the image

If you'd like to display image(s) stored within a folder of C drive on your server in view page, you can refer to the following code snippet to serve files from expected location.

app.UseStaticFiles();

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(@"C:\Users\Public\images", "employees")),
    RequestPath = "/employees"
});

In controller action

var model = new EmployeeViewModel
{
    FirstName = employeeDetails.FirstName,
    FullName = employeeDetails.FullName,
    LastName = employeeDetails.LastName,
    ImageUrl = "/employees/John.jpg"
};

For more information about serving static files and PhysicalFileProvider, please check:

  • https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1

  • https://learn.microsoft.com/en-us/aspnet/core/fundamentals/file-providers?view=aspnetcore-3.1#file-provider-implementations

like image 149
Fei Han Avatar answered Sep 05 '25 01:09

Fei Han