簡體   English   中英

如何在HTTP處理程序ashx中將文件上傳到網絡路徑?

[英]How to upload file to network path in http handler ashx?

我嘗試使用以下Silverlight應用程序代碼將文件上傳到網絡路徑:

public void ProcessRequest (HttpContext context) 
{
  //.....
  using (FileStream fs = File.Create(@"\\Server\Folder\" + filename))            
 {
   byte[] buffer = new byte[4096];
   int bytesRead;
   while ((bytesRead = context.Request.InputStream.Read(buffer, 0, buffer.Length)) != 0)
   {
      fs.Write(buffer, 0, bytesRead);
   }
 }
}

當我使用VS內置的Web服務器在調試模式下運行它時,它工作正常。 在SL端,我用url將此處理程序稱為:

UriBuilder ub = new UriBuilder("http://localhost:38700/FileUpload.ashx");

然后,我將此應用程序發布到本地IIS,並將URL更改為http://localhost/Mysite/FileUpload.ashx

然后再次運行該應用程序。 它不再工作了,但是沒有錯誤。

我猜這是因為調用File.Create的憑據不同。 所以我想在處理程序中使用特定的憑據將文件放置到目標位置。

如何對File.Create使用憑據?

我相信您將需要冒充用戶。 下面的代碼應該做到這一點。 本質上,您收集域,用戶和密碼並實例化ImpersonationMgr類。 然后調用BeginImpersonation方法。 之后,調用所需的相應WriteFile方法。 如果啟用了模擬,則WriteFile方法將斷言。 您可以對其他文件方法(例如刪除和移動)遵循類似的模式。

public class ImpersonationMgr : IDisposable

  [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType,
                                      int dwLogonProvider, out SafeTokenHandle phToken);

  [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  public static extern bool CloseHandle(IntPtr handle);

  private const int LOGON32_PROVIDER_DEFAULT = 0;
  private const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

  private readonly string userName = string.Empty;
  private readonly string domainName = string.Empty;
  private readonly string password = string.Empty;

  private SafeTokenHandle safeTokenHandle = null;
  private WindowsImpersonationContext impersonatedUser = null;

  public ImpersonationMgr(string userName, string domainName, string password)
  {
     this.userName = userName;
     this.domainName = domainName;
     this.password = password;
  }

  public void BeginImpersonation()
  {
     bool returnValue = LogonUser(userName, domainName, password, LOGON32_LOGON_NEW_CREDENTIALS,
                                  LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);
     if (returnValue == false)
     {
        int ret = Marshal.GetLastWin32Error();
        throw new System.ComponentModel.Win32Exception(ret);
     }

     impersonatedUser = WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle());
  }

  private void AssertImpersonationIsEnabled()
  {
     if(safeTokenHandle == null || impersonatedUser == null)
     {
        throw new UnauthorizedAccessException("You must call the BeginImpersonation method before attempting file write access.");
     }
  }

  public void WriteFile(string pathToFile, string fileContents)
  {
     AssertImpersonationIsEnabled();
     using (FileStream fileStream = File.Open(pathToFile, FileMode.CreateNew))
     {
        using (StreamWriter fileWriter = new StreamWriter(fileStream))
        {
           fileWriter.Write(fileContents);
        }
     }
  }

  public void WriteFile(string pathToFile, byte[] fileContents)
  {
     AssertImpersonationIsEnabled();
     using (FileStream fileStream = new FileStream(pathToFile, FileMode.Create))
     {
        fileStream .Write(fileContents, 0, fileContents.Length);
        fileStream .Flush();          
     }
  }

  public void Dispose()
  {
     Dispose(true);
     GC.SuppressFinalize(this);
  }
}

更新

   public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
   {
      private SafeTokenHandle()
         : base(true)
      {
      }


      [DllImport("kernel32.dll")]
      [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
      [SuppressUnmanagedCodeSecurity]
      [return: MarshalAs(UnmanagedType.Bool)]
      private static extern bool CloseHandle(IntPtr handle);

      protected override bool ReleaseHandle()
      {
         return CloseHandle(handle);
      }
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM