如何将json发布到webapi.netcore?

wn9m85ua  于 2022-11-19  发布在  .NET
关注(0)|答案(1)|浏览(97)
var client = new HttpClient();
var request = new HttpRequestMessage();
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var requestData = new Dictionary<string, string>
{
    { "FirstName", user.FirstName},
    { "LastName", user.LastName },
    { "Date_Of_Birth", user.Date_Of_Birth.ToString()},
    { "Gender", user.Gender},
    { "Status", user.Status.ToString()}
};
request = new HttpRequestMessage()
{
    RequestUri = new Uri("https://localhost:7169/api/User/Add"),
    Method = HttpMethod.Post,
    Content = new FormUrlEncodedContent(requestData)
};
var response = client.PostAsync(request.RequestUri,request.Content);

我当前的代码不起作用?

myzjeezk

myzjeezk1#

也许您可以将此代码简化为:

var client = new HttpClient();
 var request = new AddUserRequest
 {
    FirstName = "Test",
    LastName = "Test",
    DateOfBirth = DateTime.Now.ToString(CultureInfo.InvariantCulture) 
    //...
 };
 var result = await client.PostAsJsonAsync("https://localhost:7169/api/User/Add", request);

相关问题