【发布时间】:2019-07-11 19:01:46
【问题描述】:
我正在尝试将 asp.net core web api(已经连接到我的本地 sqlserver 并且工作正常)连接到我的 asp.net-mvc5 web 应用程序,因此当调用控制器时,它使用 API 从数据库中获取数据
现在,这就是我尝试在我的 asp.net mvc 项目中连接 api 的方式,如下所示是 homeController:
namespace AptitudeTest.Controllers
{
public class HomeController : Controller
{
string Baseurl = "http://localhost:51448";
public async Task<ActionResult> Index()
{
List<Teacher> teacher = new List<Teacher>();
//Teacher t1 = new Teacher();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource GetAllEmployees using HttpClient
HttpResponseMessage Res = await client.GetAsync("api/Admin/Get");
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var EmpResponse = Res.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing into the Employee list
teacher = JsonConvert.DeserializeObject<List<Teacher>>(EmpResponse);
}
//returning the employee list to view
return View(teacher);
}
}
我希望它以 json 对象的形式返回我的老师,但这是我得到的错误:
传入字典的模型项的类型为“System.Collections.Generic.List1[AptitudeTest.Teacher]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[AptitudeTest.Models.Teacher]”。
说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。
异常详细信息:System.InvalidOperationException:传入字典的模型项的类型为“System.Collections.Generic.List1[AptitudeTest.Teacher]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[AptitudeTest.Models.Teacher]”。
来源错误:
在执行当前 Web 请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪来识别有关异常起源和位置的信息。
【问题讨论】:
标签: sql-server asp.net-mvc asp.net-core-webapi