这是我的MVC控制器代码。
[HttpPost]
public async Task<IActionResult> InsertNewStudentAsync(ViewModel.StudentPersonalDetailsViewModel ob)
{
StudentModel obj = ViewModel.StudentPersonalDetailsViewModel.Translate(ob);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:52494/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var bodyData = ViewModel.StudentPersonalDetailsViewModel.Translate(ob);
//HttpContent ob = new HttpContent();
var response = await client.PostAsync("api/Student/InsertStudent",obj);
}
return View();
}
在var response = await client.PostAsync("api/Student/InsertStudent",obj);
行
它显示我在显示
的obj时出错错误CS1503参数2:无法从'SMS.Domain.Models.StudentModel'转换为'System.Net.Http.HttpContent'
如何将该对象传递给API的控制器。
答案 0 :(得分:2)
这是因为它期待HttpContent
派生类。
使用PostAsJsonAsync
扩展方法
var response = await client.PostAsJsonAsync("api/Student/InsertStudent",obj);
或自行转换
var json = JsonConvert.SerializeObject(obj);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("api/Student/InsertStudent", content);
这基本上就是扩展方法在幕后做的事情。
如果您不想添加其他依赖项,可以使用滚动自己的扩展方法的示例。
public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string requestUri, T obj) {
var json = JsonConvert.SerializeObject(obj);
var content = new StringContent(json, Encoding.UTF8, "application/json");
return client.PostAsync(requestUri, content);
}