簡體   English   中英

嘗試上傳文件時出現“遠程服務器返回錯誤:(401)未經授權”錯誤

[英]“The remote server returned an error: (401) Unauthorized” error when trying to upload a file

我發現了很多有關(401)未經授權的錯誤的問題,但是沒有一個問題向我解釋了如何診斷問題。

我創建了一個新的MVC ASP.net應用程序,以了解如何將文件上傳到sharepoint文件夾。 截至目前,我似乎無法將文件從C:\\ testfolder \\ file.txt復制到C:\\ testfolder \\ UploadedFiles

這是我在源文件路徑和目標文件夾中發送位置的方法:

 //Flag to indicate whether file was uploaded successfuly or not
        bool isUploaded = true;
        try
        {
            // Create a PUT Web request to upload the file.
            WebRequest request = WebRequest.Create(targetDocumentLibraryPath);

            //Set credentials of the current security context
            request.PreAuthenticate = true;
            request.UseDefaultCredentials = true;
            ICredentials credentials = new NetworkCredential( "Username", "password", "Domain"); //I used my username and password here
            request.Credentials = credentials;
            //request.Credentials = CredentialCache.DefaultCredentials;
            request.Method = "PUT";

            // Create buffer to transfer file
            byte[] fileBuffer = new byte[1024];

            // Write the contents of the local file to the request stream.
            using (Stream stream = request.GetRequestStream())
            {
                //Load the content from local file to stream
                using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))
                {
                    //Get the start point
                    int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);
                    for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))
                    {
                        stream.Write(fileBuffer, 0, i);
                    }

                }
            }

            // Perform the PUT request
            WebResponse response = request.GetResponse();

            //Close response
            response.Close();
        }
        catch (Exception ex)
        {
            //Set the flag to indiacte failure in uploading
            isUploaded = false; //The remote server returned an error: (401) Unauthorized.
        }

        //Return the final upload status
        return isUploaded; 
    }

我嘗試了以下方法:

  • 更改文件夾的權限,以便為所有用戶寫入/讀取文件夾。
  • 使用其他文件夾位置(SharePoint,本地驅動器,網絡驅動器)將文件上傳到。

關於如何解決此問題的任何想法嗎? 任何對如何調試問題的准見解也將受到贊賞。

更新:可能是我的帳戶被設置為IIS中的應用程序池帳戶。 我仍然不確定是什么問題。

這不會像代理設置那樣嗎?

您是否需要將默認代理設置添加到您的

WebRequest 

還需要添加

<system.net> 
  <defaultProxy useDefaultCredentials="true" /> 
</system.net> 

到您的網絡配置?

這可能會有所幫助。

我應該如何設置默認代理使用默認憑據?

我決定嘗試另一種方法,並使用此處描述的httpposted文件和.saveAs()

暫無
暫無

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

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