如何在.net core中传递unc凭证

How to pass unc credential in .net core

我需要使用 .net core web api 将文件保存在 unc 位置。可以使用正确的用户名和密码组合访问该位置。以下一段代码不起作用,我的意思是当我尝试创建 directory.I 时恐怕我没有以正确的方式传递用户名和密码。有人可以调查一下吗?

try
{

    var credential = new NetworkCredential("username", "password", "\\location\Test");
    var testCache = new CredentialCache
    {
        { new Uri("\\location\test"), "Basic", credential }
    };

    var folder = GetDestinationFolder(DateTime.Now, "\\location\test");
    Directory.CreateDirectory(folder); // it throws exception saying access to the path is denied    
}
catch (Exception ex)
{
    var exxx = ex.Message;
}

默认情况下,凭据继承自 IIS 应用程序池。您可以运行您的应用程序在有权访问unc路径的用户帐户下。

对于另一种解决方法,您可以尝试

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
        int dwLogonType, int dwLogonProvider, out SafeAccessTokenHandle phToken);

    const int LOGON32_PROVIDER_DEFAULT = 0;
    //This parameter causes LogonUser to create a primary token. 
    const int LOGON32_LOGON_INTERACTIVE = 2;
    // Call LogonUser to obtain a handle to an access token. 
    SafeAccessTokenHandle safeAccessTokenHandle;

    [HttpGet, Route("success")]
    public string Success()
    {
        bool returnValue = LogonUser("username","domain" ,"password",
            LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
            out safeAccessTokenHandle);

        WindowsIdentity.RunImpersonated(safeAccessTokenHandle, () =>
        {
            var folder = @"\unc path";
            Directory.CreateDirectory(folder); // it throws exception saying access to the path is denied    
        });
        return "Success Response";
    }        
}