HttpClient PostAsycn始终返回404 Not Found但控制器适用于Postman和Javascript应用程序

时间:2017-11-14 19:32:28

标签: c# asp.net-web-api dotnet-httpclient

我在控制器中有一个Post Web Api方法,它已经在工作了,我一直在测试从邮递员和我自己的网络应用程序发送文件的方法,但它现在可以工作了,但是现在我可以使用它。我试图使用Httpclient从控制台应用程序发送文件,但总是得到404。

控制器方法

public async Task<IHttpActionResult> Post()
    {
        FileServerConfig config = FileServerConfiguration.ObtenerConfiguracion(ConfigurationManager.AppSettings);

        var path = string.Empty;
        try
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                return StatusCode(HttpStatusCode.UnsupportedMediaType);
            }

            var filesReadToProvider = await Request.Content.ReadAsMultipartAsync();

            foreach (var stream in filesReadToProvider.Contents)
            {
                IFileServerWrapper _cliente = FileServerConfiguration.CrearCliente(config);
                var name = stream.Headers.ContentDisposition.FileName.Replace("\"", "").Replace("\\", "");
                var fileUploaded = await _cliente.FileUpload(path, await stream.ReadAsStreamAsync(), name, false);
            }
            return Ok();
        }
        catch (HttpException httpex)
        {
            if (httpex.GetHttpCode() == (int)HttpStatusCode.Conflict)
            {
                return Conflict();
            }
            else
            {
                return InternalServerError(httpex);
            }
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }

    }

控制台应用

static void Main(string[] args)
    {
        string filePath = @"C:\Software\itextTifftoPDF.rar";
        using (var client = new HttpClient())
        using (var content = new MultipartFormDataContent())
        {
            // Make sure to change API address
            //client.BaseAddress = new Uri("http://localhost:80/FileServerAPI/");
            client.DefaultRequestHeaders.Add("Accept-Language", "en-GB,en-US;q=0.8,en;q=0.6,ru;q=0.4");
            client.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            // Add first file content 
            var fileContent1 = new ByteArrayContent(File.ReadAllBytes(filePath));
            fileContent1.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                FileName = "itextTifftoPDF.rar"
            };

            content.Add(fileContent1);

            // Make a call to Web API
            var result = client.PostAsync("http://localhost/FileServerAPI/api/File", content).Result;

            Console.WriteLine(result.StatusCode);
            Console.ReadLine();
        }
    }

1 个答案:

答案 0 :(得分:-2)

最后我找到了解决方案。代码是丑陋的,因为它只是为了确保它有效,但我希望它可以帮助其他人解决同样的问题。

string filePath = @"C:\temp\webdavtest.txt";
        using (HttpClient httpClient = new HttpClient())
        {
            using (MultipartFormDataContent content =
                             new MultipartFormDataContent())
            {
                using (FileStream stream = File.Open(
                      filePath, FileMode.Open, FileAccess.Read))
                {
                    using (StreamContent streamConent =
                                        new StreamContent(stream))
                    {
                        content.Add(
                        streamConent, "webdavtest.txt", "webdavtest.txt");
                        var result = await httpClient.PostAsync("http://localhost:3983/api/File?path=/nivel5/", content);
                        return result.StatusCode.ToString();
                    }
                }
            }
        }