我想要做一個多部分形式的帖子在C#中使用HttpClient,我發現下面的代碼不起作用。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 = "[email protected]",
To = new[] { "[email protected]", "[email protected]" },
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);
}
}
}
}
}
我真的不知道爲什麼它不工作。我得到文件發佈到端點,但body(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 }
);
}
爲什麼有人會投這個票?我提供了代碼,並解釋了我想要做的事情。這是一個明確的說法。 –
如果您也顯示服務器端代碼,那麼可能會有所幫助,因此我們可以看到您如何嘗試讀取它。 –
服務器端代碼只是一個ASP.NET MVC端點,其中模型作爲輸入類型。那裏沒什麼特別的,但我放下來表示沒有詭計。 –