Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过ASP.NET MVC WebApi上载文件的客户端代码_C#_Asp.net Mvc_File Upload_Asp.net Web Api2 - Fatal编程技术网

C# 通过ASP.NET MVC WebApi上载文件的客户端代码

C# 通过ASP.NET MVC WebApi上载文件的客户端代码,c#,asp.net-mvc,file-upload,asp.net-web-api2,C#,Asp.net Mvc,File Upload,Asp.net Web Api2,我正在尝试编写代码,通过WinForm应用程序将文件上载到WebApi WebApi代码如下所示: [HttpPost] [Route("UploadEnvelope")] [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] public Task<HttpResponseMessage> PostUploadEnvelope() { HttpRequestMessage request = this

我正在尝试编写代码,通过WinForm应用程序将文件上载到WebApi

WebApi代码如下所示:

[HttpPost]
[Route("UploadEnvelope")]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
public Task<HttpResponseMessage> PostUploadEnvelope()
{
    HttpRequestMessage request = this.Request;
    if (!request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
    var provider = new MultipartFormDataStreamProvider(root);

    var task = request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(o =>
        {
            foreach (MultipartFileData fileData in provider.FileData)
            {
                if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                {
                    return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
                }
                string fileName = fileData.Headers.ContentDisposition.FileName;
                if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                {
                    fileName = fileName.Trim('"');
                }
                if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                {
                    fileName = Path.GetFileName(fileName);
                }
                File.Move(fileData.LocalFileName, Path.Combine(root, fileName));
            }

            return new HttpResponseMessage()
            {
                Content = new StringContent("Files uploaded.")
            };
        }
    );
    return task;
}

欢迎任何帮助或建议。提前谢谢

首先,您使用的是用于阅读的
Get
方法。您必须改用
Post

请尝试以下操作:

public static string UploadEnvelope(string  filePath,string token, string url)
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        using (var content = new MultipartFormDataContent("Envelope" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
        {
            content.Add(new StreamContent(new MemoryStream(File.ReadAllBytes(filePath))), "filename", "filename.ext");
            using (var message = await client.PostAsync(url + "/api/Envelope/UploadEnvelope", content))
            {
                var input = await message.Content.ReadAsStringAsync();
                return "success";
            }
        }
    }
}

注意:对于大文件,您必须更改IIS上的配置
web.config

回答得很好!上帝保佑你!你能看到这个吗?
public static string UploadEnvelope(string  filePath,string token, string url)
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        using (var content = new MultipartFormDataContent("Envelope" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
        {
            content.Add(new StreamContent(new MemoryStream(File.ReadAllBytes(filePath))), "filename", "filename.ext");
            using (var message = await client.PostAsync(url + "/api/Envelope/UploadEnvelope", content))
            {
                var input = await message.Content.ReadAsStringAsync();
                return "success";
            }
        }
    }
}