我如何在MVC中使用WebApi服务

时间:2018-09-11 04:52:24

标签: c# asp.net-mvc-4

这里我正在尝试访问WebApi中的Mvc服务,但出现了错误:

  

asSeverity代码说明项目文件行错误CS0029无法   隐式地将类型'string'转换为   'System.Collections.Generic.IEnumerable'

    IEnumerable<MasterTab> resResult = result.Content.ReadAsStringAsync().Result;
 public ActionResult Index()
        {
            using(var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:54040/Api/Marketing/");
                var responseTask = client.GetAsync("GetMarketing");
                responseTask.Wait();
                var result = responseTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    IEnumerable<MasterTab> resResult = result.Content.ReadAsStringAsync().Result;
                }
                else
                {
                    students = Enumerable.Empty<MasterTab>();ModelState.AddModelError(string.Empty, "Server Error Please Conatct Admin");
                }
            }
            return View(students);
        }

2 个答案:

答案 0 :(得分:2)

无论哪种方式,我们都可以直接从您的ApiController控制器调用MVC

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var listOfFiles = new MarketingController().GetMarketing();

        return View(listOfFiles);
    }
}

如果我们在同一解决方案中将WebApi作为一个不同的项目,那么可以像下面这样从MVC控制器中调用它:

public async Task<ActionResult> Index()
        {
            string apiUrl = "http://localhost:58764/api/Marketing/GetMarketing";

            using (HttpClient client=new HttpClient())
            {
                client.BaseAddress = new Uri(apiUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync(apiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsStringAsync();
                    EntityType entity = Newtonsoft.Json.JsonConvert.DeserializeObject<EntityType>(data);

                }


            }
            return View();

        }

答案 1 :(得分:1)

您不能将类型字符串转换为MasterTab类型。我猜想WebApi服务以JSON格式返回数据。尝试使用Newtonsoft.Json将字符串响应反序列化为MasterTab集合。

https://www.newtonsoft.com/json