Access a UNC path with .NET Core Web API

58 Views Asked by At

I have an endpoint that access a remote folder (UNC path) with some images. Locally, I have been able to do it and get the image, but if the Web Api is published in IIS, the return says my credentials are incorrect.

I was able to solve this in a Web Forms application, using DllImport and impersonating an administrator, but the implementations differ and they are in different computers, even thou the remote folder is the same.

I wasn't able to replicate the solution in the Web Api project using NetworkCredential and WindowsIdentity.RunImpersonated.

I am basically doing this, without the credentials part:

byte[] imageBytes = System.IO.File.ReadAllBytes(uncPath);
return File(imageBytes, "image/png");

Both IIS are already configured with the user and the access, unless I am missing something.

Thanks in advance.

1

There are 1 best solutions below

0
YurongDai On

The following code example shows how to use credentials to configure the static files middleware:

// HARDCODING FOR DEMO ONLY - Use either Azure Key Vault or some other secret manager

var sourceCredentials = 
    new NetworkCredential { Domain = "domain", UserName = "user", Password = "pass" };
using (new NetworkConnection("\\\\Network\\Shared", sourceCredentials))
{

    // to serve static froms from \\network\shared location

    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
                    Path.Combine("\\\\Network\\Shared"))
    });
}

This method uses a custom NetworkConnection class to simulate a network connection and uses this connection in the static file middleware. The purpose of this method is to establish a connection to the shared network path using the specified credentials when the application starts, so that the application can access static files in the shared folder during startup.

It is important to note that the credentials in this method are hardcoded in the code in clear text. This is not safe in a real production environment. In a production environment, you should keep those credentials at some secured location (like key vault).

Reference links:

How to simulate a virtual directory in ASP.NET Core app hosted on IIS for debugging?

How to use network shared path with credentials as static files folder in asp.net core