Web api not working with mvc
Hi,My application contains a web api and mvc project
I have create a web api connected database with entity framework and tested like this
http://localhost:1547/api/employee/
it returns
[{"EmployeeID":1,"Name":"Ram","Position":"SW Engineer","Age":29,"Salary":80000},{"EmployeeID":2,"Name":"Krishnan","Position":"Admin","Age":34,"Salary":9000}]
then I have added an mvc project in same solution
create class file for accessing web api data like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Http;
using System.Net.Http.Headers;
namespace Mvc
{
public static class GlobalVariables
{
public static HttpClient WebApiClient = new HttpClient();
static GlobalVariables()
{
WebApiClient.BaseAddress = new Uri("http://localhost:1547/api");
WebApiClient.DefaultRequestHeaders.Clear();
WebApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
}
}
next I have added a controller in mvc(Employeecontroller) and added following code
public ActionResult Index()
{
IEnumerable<MvcEmployeeModel> empList;
HttpResponseMessage response = GlobalVariables.WebApiClient.GetAsync("Employee").Result;
empList = response.Content.ReadAsAsync<IEnumerable<MvcEmployeeModel>>().Result;
return View(empList);
}
next created a view for the above index
@model IEnumerable<Mvc.Models.MvcEmployeeModel>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.EmployeeID)
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Position)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.Salary)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.EmployeeID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Position)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.Salary)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
finally set the property and start both webapi and mvc projects
and run like this
http://localhost:1548/employee
an error has shown
Additional information: No MediaTypeFormatter is available to read an object of type 'IEnumerable`1' from content with media type 'text/html'.
How to solve this
Regards
Baiju