user8518202
user8518202

Reputation:

How can i Consume WebApi Service in mvc

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);
        }

Upvotes: 0

Views: 73

Answers (2)

Tiber Septim
Tiber Septim

Reputation: 335

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

Upvotes: 1

Hossein
Hossein

Reputation: 3113

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();

        }

Upvotes: 3

Related Questions