我正在尝试使用 C# 中的 HttpClient 进行多部分表单发布,但发现以下代码不起作用。
重要的:
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)永远不会到达那里。难道我做错了什么?
服务器端代码请求:
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 }
);
}