C#中的HttpClient多部分表单发布 [英] HttpClient Multipart Form Post in C#

查看:106
本文介绍了C#中的HttpClient多部分表单发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#中的HttpClient进行多部分表单发布,并发现以下代码不起作用。

I'm trying to do a multipart form post using the HttpClient in C# and am finding the following code does not work.

重要提示:

var jsonToSend = JsonConvert.SerializeObject(json, Formatting.None, new IsoDateTimeConverter());
var multipart = new MultipartFormDataContent();
var body = new StringContent(jsonToSend, Encoding.UTF8, "application/json");

multipart.Add(body);
multipart.Add(new ByteArrayContent(File.ReadAllBytes("test.txt")), "test", "test.txt");

var httpClient = new HttpClient();
var response = httpClient.PostAsync(new Uri("http://localhost:55530"), multipart).Result;

完整程序

namespace CourierMvc.Worker
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine("Hit any key to make request.");
                Console.ReadKey();

                try
                {
                    var request = new RestRequest(Method.POST)
                    {
                        Resource = "http://localhost:55530"
                    };

                    var json = new CourierMessage
                    {
                        Id = Guid.NewGuid().ToString(),
                        Key = "awesome",
                        From = "khalid@home.com",
                        To = new[] { "me@test.com", "you@test.com" },
                        Subject = "test",
                        Body = "body",
                        Processed = DateTimeOffset.UtcNow,
                        Received = DateTime.Now,
                        Created = DateTime.Now,
                        Sent = DateTime.Now,
                        Links = new[] { new Anchor { Link = "http://google.com" }, new Anchor { Link = "http://yahoo.com" } }
                    };

                    var jsonToSend = JsonConvert.SerializeObject(json, Formatting.None, new IsoDateTimeConverter());
                    var multipart = new MultipartFormDataContent();
                    var body = new StringContent(jsonToSend, Encoding.UTF8, "application/json");

                    multipart.Add(body);
                    multipart.Add(new ByteArrayContent(File.ReadAllBytes("test.txt")), "test", "test.txt");

                    var httpClient = new HttpClient();
                    var response = httpClient.PostAsync(new Uri("http://localhost:55530"), multipart).Result;

                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
    }
}

我真的不知道为什么它不起作用。我将文件发布到端点,但是主体(json)从未到达那里。我做错了吗?

I really have no idea why it doesn't work. I get the file to post to the endpoint, but the body (json) never gets there. Am I doing something wrong?

服务器端代码请求:

namespace CourierMvc.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return Content("Home#Index");
        }


        [ValidateInput(false)]
        public ActionResult Create(CourierMessage input)
        {
            var files = Request.Files;

            return Content("OK");
        }

    }
}

路由配置:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Create", id = UrlParameter.Optional }
    );

}


推荐答案

我看到的问题是 MultipartFormDataContent 请求消息将始终将请求的内容类型设置为 multipart / form-data。结束对json进行编码并将其放入请求中,就像模型绑定程序一样只是看起来为字符串。

So the problem I'm seeing is that the MultipartFormDataContent request message will always set the content type of the request to "multipart/form-data". Endcoding json and placing that into the request only "looks" like to the model binder as a string.

您的选择是:


  • 让您的mvc操作方法接收字符串并反序列化到对象中

  • 将模型的每个属性作为表单的一部分发布

  • 创建将处理您的请求的自定义模型活页夹。

  • 将操作拆分为两个帖子,首先发送json元数据,另一个发送文件。服务器的响应应发送一些ID或密钥,以使两个请求相关。

  • have your mvc action method receive a string and deserialize into your object
  • post each property of your model as a form part
  • create a custom model binder that will handle your request.
  • Breakup the operation into two posts, first sends the json metadata, the other sends the file. The response from the server should send some id or key to correlate the two requests.

通过 RFC文档 MSDN文档,如果您将 MultipartFormDataContent 替换为 MultipartContent 。但是我还没有测试过。

Reading through the RFC document and the MSDN documentation you may be able to do this, if you replace MultipartFormDataContent with MultipartContent. But I have not tested this yet.

这篇关于C#中的HttpClient多部分表单发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆