Asp.Net WebApi - 发布文件

时间:2018-02-15 18:41:48

标签: c# rest file post asp.net-web-api

任何人都可以告诉我这个问题吗?我一直试图将文件和一些参数发布到WebApi,但使用multipart / form-data根本不起作用。我能做什么?以下代码来自:

- 客户端 -

public string Put(string appkey, string senha)
    {
        string url = $"{"http://localhost:59701"}/api/Ocr";
        HttpClient httpClient = new HttpClient();
        httpClient.Timeout = new TimeSpan(1, 1, 1);
        string xml = "";


        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));

            using (var multipartFormDataContent = new MultipartFormDataContent())
            {
                var values = new[]
                {
            new KeyValuePair<string, string>("Id", Guid.NewGuid().ToString()),
            new KeyValuePair<string, string>("Key", "awesome"),
            new KeyValuePair<string, string>("From", "khalid@home.com")
             //other values
        };

                foreach (var keyValuePair in values)
                {
                    multipartFormDataContent.Add(new StringContent(keyValuePair.Value),
                        String.Format("\"{0}\"", keyValuePair.Key));
                }

                multipartFormDataContent.Add(new ByteArrayContent(Arquivo), '"' + "File" + '"', NomeArquivo);

                var result = client.PutAsync(url, multipartFormDataContent).Result;
            }
        }

        return xml;
    }

-WebApi -

public class OcrController : ApiController
{
    [HttpPut]
    public void Extrair(CourierMessage input)
    {
        //do anything
    }
}

public class CourierMessage
{
    public string Id { get; set; }
    public string Key { get; set; }
    public string From { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
    public DateTimeOffset Processed { get; set; }
    public DateTime Received { get; set; }
    public DateTime Created { get; set; }
    public DateTime Sent { get; set; }
    public HttpPostedFileBase File { get; set; }
}

有没有办法将每个属性绑定到对象,就像我们在MVC中一样?

0 个答案:

没有答案