想要将对象从MVC控制器传递给web api控制器

时间:2017-06-21 13:50:27

标签: c# asp.net-core-mvc asp.net-core-webapi

这是我的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的控制器。

1 个答案:

答案 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);    
}