【问题标题】:Writing files from Asp.Net to Azure File Storage fails将文件从 Asp.Net 写入 Azure 文件存储失败
【发布时间】:2016-05-09 15:52:09
【问题描述】:

我有一个带有 IIS 设置的 Azure VM,它托管我的 ASP.Net 网站。

我希望能够使用普通的 Windows 类库 (System.IO) 从网络共享(Azure 文件存储)读取和写入文档/文件。我不想使用 Azure 存储客户端库或 Azure Storage Rest API。

我已按照this article 中的详细信息安装了共享并保留了我的凭据。

安装驱动器并保留我的凭据后,我将我的网站指向我的共享驱动器,以使用我的共享驱动器来执行所有与文档管理相关的功能。下载文件完美无缺。但是,当我尝试创建文件夹或将文档写入网络共享时,我会立即收到错误消息。

我收到的错误是:

找不到路径“F:[RestOfThePathHere]”的一部分。 堆栈跟踪:

[DirectoryNotFoundException: 找不到路径的一部分 'F:\Test\MyThing\Clients\TheirStuff'。]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +338 System.IO.Directory.InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, Boolean checkHost) +1578
System.IO.Directory.InternalCreateDirectoryHelper(字符串路径,布尔值 checkHost) +213
MyStuff.FileHandling.FileExtenders.SaveToFile(Byte[] ByteArray, String 目录,字符串文件名)+116
MyStuff.TheirStuff.BLL.TheirStuffTestClient.RunEnquiry(ClientBase 客户端,字符串结果类型)+3776
MyStuff.MyThing.UI.Views.ClientController.CreditCheck(Int64 id) +42
lambda_method(闭包, ControllerBase, Object[]) +114
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext 控制器上下文,IDictionary2 parameters) +242
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary
2 参数)+39
System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +12
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +139
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +112 System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +452 System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +37 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +241
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid
1.CallEndDelegate(IAsyncResult 异步结果)+111
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +19
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +51
System.Web.Mvc.Async.WrappedAsyncVoid
1.CallEndDelegate(IAsyncResult 异步结果)+111
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

或者,当我使用 UNC 寻址时

找不到网络路径。 StackTrace:[IOException:找不到网络路径。 ]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +14382132 System.IO.Directory.InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, Boolean checkHost) +1578 System.IO.Directory.InternalCreateDirectoryHelper(字符串路径,布尔值 checkHost) +213
MyStuff.FileHandling.FileExtenders.SaveToFile(Byte[] ByteArray, String 目录,字符串文件名)+116
MyStuff.TheirStuff.BLL.TheirStuffTestClient.RunEnquiry(ClientBase 客户端,字符串结果类型)+3776
MyStuff.MyThing.UI.Views.ClientController.CreditCheck(Int64 id) +42
lambda_method(闭包, ControllerBase, Object[]) +114
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext 控制器上下文,IDictionary2 parameters) +242
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary
2 参数)+39
System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +12
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +139
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +112 System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +452 System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +37 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +241
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
System.Web.Mvc.Async.WrappedAsyncVoid
1.CallEndDelegate(IAsyncResult 异步结果)+111
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +19
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +51
System.Web.Mvc.Async.WrappedAsyncVoid
1.CallEndDelegate(IAsyncResult 异步结果)+111
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

更新 - 我当前的代码

MVC 控制器方法

public ActionResult Upload(DocumentUploadVM VM, long ClientId, long ContextInstanceId, long DocumentClassId, long TaskId)
    {
            var documentClass = docMan.Get_DocumentClass(DocumentClassId);

            var errors = new List<string>();

            if (VM.File == null || VM.File.ContentLength == 0)
                errors.Add("You haven't selected a file to upload");
            else if (!documentClass.MimeTypeAllowed(VM.File.ContentType, docMan))
                errors.Add("The file type is forbidden");

            if (errors.Count == 0 && ModelState.IsValid)
            {
                var path = settings.GetSettingValueAsString("Document Management: Client Documents Root Path").TrimEnd('\\') + "\\Uploads\\";
                var pvtFileName = new Random().Next().ToString() + "." + VM.File.FileName.Split('.').Last();
                var targetURI = Path.Combine(path, pvtFileName);

                MemoryStream ms = new MemoryStream();
                VM.File.InputStream.CopyTo(ms);

                IFileHandler fh = FileHandlingFactory.Create();
                fh.SaveFile(ms, targetURI);

                docMan.Add_Document(
                    new FileItem
                    {
                        FilePathOnServer = path,
                        PublicFileName = VM.File.FileName,
                        PrivateFileName = pvtFileName,
                        MimeType = VM.File.ContentType
                    },
                    docMan.Get_ContextInstance(ContextInstanceId),
                    new List<DocumentClass> { documentClass });
            }
            else
            {
                TempData["errors"] = errors;
            }

            //TODO: In case of model errors, this call will suppress the errors.  Look to TempData / PRG pattern to maintain model state over redirect.
            return
              RedirectToAction("ListClientDocuments", new { ClientId = ClientId, TaskId = TaskId });
        }

IFileHandler.SaveFile 实现

public override void SaveFile(MemoryStream MemoryStream, string Fullpath)
    {
        var directory = Fullpath.Substring(0, Fullpath.LastIndexOf('\\')).TrimEnd('\\');
        var fileName = Fullpath.Replace(directory, "").Trim('\\');
        MemoryStream.ToArray()
        .SaveToFile(directory, fileName);
    }

PS - 请原谅糟糕的代码和公然无视 C# 编码标准。我写这篇文章的时候是个菜鸟。但是,这段代码在用于处理本地文件存储时还没有给我带来任何问题。

【问题讨论】:

  • 这将有助于查看用于建立连接并尝试文件访问/创建的相关代码。当然,编辑任何私密的内容。
  • 你用过“网络使用”吗? “净使用”是相对于您运行“净使用”的用户而言的。所以你的网络应用程序不会看到它(除非你用同一个用户运行网络应用程序)。
  • @FabrizioAccatino 是的,我使用了“网络使用”,但我没有使用运行 Web 应用程序的同一用户登录。有没有其他方法可以使用我的默认 iis 用户实现这一目标?
  • @CraftBeerHipsterDude 我认为您必须使用“代码净使用”。类似stackoverflow.com/questions/5433570/…
  • @ByronJones 代码按要求添加

标签: asp.net azure azure-virtual-machine smb azure-storage-files


【解决方案1】:

我认为您可能想尝试创建一个映射到存储帐户用户的本地用户,然后将此用户添加到 IIS_IUSRS 组。

详情请参阅此博客 http://blogs.iis.net/davidso/azurefile

-杰森

【讨论】:

  • 感谢您的回答。我真的希望 MS 能让我们更轻松地将我们的网站托管为 Azure 网站而不是虚拟机,而不必求助于 SMB 文件存储的专业 API(换句话说,使用普通 System.IO 来读取和写入共享存储) )。
  • 这真的有效吗?出于某种原因,我无法让那篇文章正常工作。
  • OMG - 非常感谢您的回复。完全让我开心! ✨??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-21
  • 2021-01-09
  • 2019-11-27
  • 2017-08-18
  • 1970-01-01
  • 2015-05-03
  • 1970-01-01
相关资源
最近更新 更多