2017-06-21 155 views
1

這是我的MVC控制器代碼。想要將對象從MVC控制器傳遞到Web API控制器

[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);

它表示我示出在物鏡的錯誤

錯誤CS1503參數2:不能從 'SMS.Domain.Models.StudentModel' 轉換爲' System.Net.Http.HttpContent'

如何將該對象傳遞給我的API控制器。

回答

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);  
} 
相關問題