WebAPI调用无法在ASP.NET MVC 5应用程序中工作

时间:2016-09-08 11:21:26

标签: c# asp.net asp.net-mvc asp.net-web-api asp.net-mvc-5

这里我的Web API调用在浏览器中运行良好,

enter image description here

我想使用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();
    }
}

但是一旦我编译就会出现这种错误

enter image description here

这样的东西
  

无法加载文件或程序集'System.Net.Http.Formatting,   Version = 5.2.3.0,Culture = neutral,PublicKeyToken = 31bf3856ad364e35'或   其中一个依赖项。定位程序集的清单定义   与装配参考不匹配。

然后我发现这个answer无效,我该如何解决这个问题呢?

1 个答案:

答案 0 :(得分:0)

您必须在解决方案中添加System.Net.Http.Formatting.dll引用