【问题标题】:Uploading a file from .NET application to a Web API POST endpoint将文件从 .NET 应用程序上传到 Web API POST 端点
【发布时间】:2013-10-31 14:55:25
【问题描述】:

我想使用 Web API 构建一些端点供应用程序使用。我希望它做的第一项工作是允许客户端将文件上传到服务器。

客户端将运行某种 .NET 应用程序,可能是控制台应用程序或其他东西。它不会是使用表单元素或文件输入的网页。

我认为 Web API 应该是这样的:

public class FileController : ApiController
{
    public bool Post(File newFile)
    {
        return true;
    }
}

将其用作模型类:

public class File
{
    public string name { get; set; }
    public Stream uploadStream { get; set; }
}

我确定这是非常错误的,但这是我的第一个 Web API。

我正在尝试在控制台应用程序中对此进行测试:

namespace TestFileUpload
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting the test...");

            using (FileStream readstream = new FileStream(@"C:\\Test\Test2.txt", FileMode.Open, FileAccess.Read))
        {
            WebAPI.Classes.File newFile = new WebAPI.Classes.File()
            {
                name = "Test.txt",
                uploadStream = readstream
            };

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:50326");
            client.DefaultRequestHeaders.Accept.Add(
                                new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response;
            response = client.PostAsJsonAsync("http://localhost:50326/api/file", newFile).Result;
            Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);

        };

            Console.ReadLine();
        }
    }
}

现在我在尝试获取响应时遇到超时错误: “从 'System.IO.FileStream' 上的 'ReadTimeout' 获取值时出错。”

帮助?

【问题讨论】:

    标签: asp.net http file-upload asp.net-web-api


    【解决方案1】:

    客户端使用 Web API 服务的方法有很多,但最直接的方法是使用 Web API 客户端库。也许您应该考虑构建一个简单的 get 方法,该方法在跳转到文件上传之前返回一个对象。

    Web API from .NET Client

    您不能添加服务引用,因为 Web API 不公开 wsdl。

    【讨论】:

    • 谢谢。请参阅更新的问题;我现在正在使用您指出的建议,但我没有看到任何 http 请求发出。
    • 首先,基地址看起来不对。它应该只是基础,例如“localhost:50326”。其次,必须有一个异常,否则 Result 属性会提示我们哪里出了问题。他们说什么?很难猜...
    • 更新了问题。我在 FileStream 上遇到异常。
    猜你喜欢
    • 1970-01-01
    • 2015-03-07
    • 2023-01-21
    • 2016-10-15
    • 2011-09-04
    • 2017-06-06
    • 2018-12-11
    • 2010-09-21
    • 1970-01-01
    相关资源
    最近更新 更多