从ASP.NET web api上载带有post的文件会在发布到Azure而不是localhost时引发错误

本文关键字:Azure 错误 localhost api web NET ASP 上载 文件 post | 更新日期: 2023-09-27 18:00:12

我有一个web api,在这里我将图像发布到我的web api中的一个文件夹中,在本地执行时它运行良好,但在在线发布web api时它不起作用,并抛出以下错误消息"将MIME多部分主体部分写入输出流时出错"。我见过一些人有类似的问题,但我一直没能解决,所以我把代码放在那里,希望有人能注意到可能是什么原因造成的!这是代码:

 public async Task<HttpResponseMessage> Post()
    {
        // Check whether the POST operation is MultiPart?
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        // Prepare CustomMultipartFormDataStreamProvider in which our multipart form
        // data will be loaded.
        string fileSaveLocation = HttpContext.Current.Server.MapPath("~/App_Data");
        CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
        List<string> files = new List<string>();
        try
        {
            // Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
            //Here the code goes down to public class CustomMultipartFormDataStreamProvider and runs that code and then jump back here. When it gets back here is when the Error is Thrown
            await Request.Content.ReadAsMultipartAsync(provider);
            foreach (MultipartFileData file in provider.FileData)
            {
                files.Add(Path.GetFileName(file.LocalFileName));
            }
            // Send OK Response along with saved file names to the client.
            return Request.CreateResponse(HttpStatusCode.OK, files);
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }
}

public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    public CustomMultipartFormDataStreamProvider(string path) : base(path) { }
    public override string GetLocalFileName(HttpContentHeaders headers)
    {
        return headers.ContentDisposition.FileName.Replace("'"", string.Empty);
    }
}

代码来自http://www.intstrings.com/ramivemula/articles/file-upload-using-multipartformdatastreamprovider-in-asp-net-webapi/在那里你可以阅读更多关于代码的信息。非常感谢任何帮助或意见,谢谢!

从ASP.NET web api上载带有post的文件会在发布到Azure而不是localhost时引发错误

我不确定您能否将数据存储在App_data中。如果您将所有文件存储在Blob存储中,效果会好上千倍。如果你需要帮助,我会帮忙的。

关注这篇文章,你就会让它运转起来。

https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-blobs/

确保首先上载映像文件的虚拟目录(下面的示例为~/App_Data目录)在物理上存在。发布项目时,它可能不在输出文件中。

string fileSaveLocation = HttpContext.Current.Server.MapPath("~/App_Data"); CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);