0

Here I'm trying to access WebApi Service in Mvc but im geeting error :

asSeverity Code Description Project File Line Error CS0029 Cannot implicitly convert type 'string' to '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); } 
1
  • IEnumerable<MasterTab> resResult = result.Content.ReadAsStringAsync().Result; Here return type is string. SO, what you need to do is first use string result = assign result; then convert it using newtonsoft or other libraries to IEnumerable<MasterTab> Commented Sep 11, 2018 at 4:59

2 Answers 2

3

Either way, then we can call the ApiController directly from your MVC controller:

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

If we have our WebApi as a different project altogether in the same solution then we can call the same from MVC controller like below:

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(); } 
Sign up to request clarification or add additional context in comments.

Comments

1

You can't cast type string as type MasterTab. I guess the WebApi service returns data in JSON format. Try to use Newtonsoft.Json to deserialize string response into MasterTab collection.

https://www.newtonsoft.com/json

Comments