【发布时间】:2017-01-16 07:21:36
【问题描述】:
我的 Web API 调用在浏览器中运行良好,
我想用 MVC 做前端所以我只创建 mvc 5 应用程序业务逻辑,如下所示
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using ProductApp.Core.Entities;
using System.Net.Http.Headers;
namespace ProductApp.MVC.Models
{
public class ProductClient
{
private string BASE_URL = "http://localhost:11661/api/Products";
public IEnumerable<Product> findAll()
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("product").Result;
if (response.IsSuccessStatusCode)
return response.Content.ReadAsAsync<IEnumerable<Product>>().Result;
return null;
}
catch
{
return null;
}
}
}
然后是视图
public class ProductController : Controller
{
// GET: Product
public ActionResult Index()
{
ProductClient pc = new ProductClient();
ViewBag.listproducts = pc.findAll();
return View();
}
}
但是一旦我编译这个得到这种错误
有点像
无法加载文件或程序集'System.Net.Http.Formatting, 版本=5.2.3.0,文化=中性,PublicKeyToken=31bf3856ad364e35' 或 它的依赖项之一。定位程序集的清单定义 与程序集引用不匹配。
然后我发现这个answer 不起作用,我该如何解决这个问题?
【问题讨论】:
-
删除对
System.Net.*的所有代码引用并运行Install-Package Microsoft.AspNet.WebApi.Client清理并重建您的项目 -
您正在将 upp C# MVC 控制器与 Web API ApiController 混合使用。它们不一样。阅读此asp.net/web-api/overview/getting-started-with-aspnet-web-api/…
-
@MarcusH 我对这项技术很陌生,基本上我所做的是获取 WEB API URL,然后在
findall方法下的ProductClient类上处理它,然后创建 MVC 控制器并创建它ProductClient对象调用findall方法,有错请指教
标签: c# asp.net asp.net-mvc asp.net-web-api asp.net-mvc-5