System.Net.Http.UnsupportedMediaTypeException: 'No MediaTypeFormatter is available to read an object of type 'IEnumerable`1' from content with media type 'text/html'.'

Amritpal Singh 60 Reputation points
2023-06-07T01:10:48.87+00:00

I am getting Unsupported Media Type Exception whenever I am doing a get request on MVC side on http://localhost:52541/Employee/Index . Please check my code and help me to solve the issue

EmployeeController.cs from MVC

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Web;

using System.Web.Mvc;

using WebAppMvc.Globals;

using WebAppMvc.Models;

namespace WebAppMvc.Controllers

{

public class EmployeeController : Controller

{


    

    public ActionResult Index()

    {

        IEnumerable<MvcEmployee> empList;

        HttpResponseMessage response = GlobalVariables.WebApiClient.

            GetAsync("Employee").Result;

		empList = response.Content.ReadAsAsync

            <IEnumerable<MvcEmployee>>().Result;

        return View(empList);

    }

}

}

// EmployeeController.cs from API

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAppAPI.Models;
using System.Data.Entity.Infrastructure;
using System.Web.Http.Description;

namespace WebAppAPI.Controllers
{
	public class EmployeeController : ApiController
	{
		private TSQL2012Entities db = new TSQL2012Entities();

		public IQueryable<tblEmployee> GetTblEmployees()
		{
			return db.tblEmployees;
		}

		public IHttpActionResult GettblEmployees(int id)
		{
			tblEmployee myEmp = db.tblEmployees.Find(id);

			if (Convert.ToString(myEmp).Length == 0 || myEmp == null)
			{
				return NotFound();
			}

			return Ok(myEmp);
		}

		public IHttpActionResult PuttblEmployees(int id, tblEmployee tblEmployees)
		{

			if (id != tblEmployees.emp_id)
			{
				return BadRequest();
			}

			db.Entry(tblEmployees).State = System.Data.Entity.EntityState.Modified;



			try
			{
				db.SaveChanges();
			}
			catch (DbUpdateConcurrencyException)
			{
				if (!tblEmployeesExists(id))
				{
					return NotFound();
				}
				else
				{
					throw;
				}
			}

			return StatusCode(HttpStatusCode.NoContent);
		}


		// POST api/Employee
		[ResponseType(typeof(tblEmployee))]
		public IHttpActionResult PostEmployee(tblEmployee employee)
		{

			db.tblEmployees.Add(employee);
			db.SaveChanges();

			return CreatedAtRoute("DefaultApi", new { id = employee.emp_id }, employee);
		}

		// DELETE api/Employee/5
		[ResponseType(typeof(tblEmployee))]
		public IHttpActionResult DeleteEmployee(int id)
		{
			tblEmployee employee = db.tblEmployees.Find(id);
			if (employee == null)
			{
				return NotFound();
			}

			db.tblEmployees.Remove(employee);
			db.SaveChanges();

			return Ok(employee);
		}


		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				db.Dispose();
			}
			base.Dispose(disposing);
		}
		private bool tblEmployeesExists(int id)
		{
			return db.tblEmployees.Count(e => e.emp_id == id) > 0;
		}

	}
}

// GlobalVariable.cs from MVC using System.Net.Http; using System.Net.Http.Headers; using System.Web;

namespace WebAppMvc.Globals {

public class GlobalVariables
{
	public static HttpClient WebApiClient = new HttpClient();

	static GlobalVariables()
	{
		WebApiClient.BaseAddress = new Uri("http://localhost:52541/api/");
		WebApiClient.DefaultRequestHeaders.Clear();
		WebApiClient.DefaultRequestHeaders.Accept.Add
			(new MediaTypeWithQualityHeaderValue("application/json"));
	}
}

}

// MvcEmployee.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web;

namespace WebAppMvc.Models {

public class MvcEmployee
{
	public int emp_id { get; set; }

	[Required (ErrorMessage ="Please enter your name")]
	[DataType (DataType.Text)]
	public string emp_name { get; set; }

	[Required (ErrorMessage = "Please enter your email")]
	[DataType (DataType.EmailAddress)]
	public string emp_email { get; set; }
	public string emp_password { get; set; }
	public string emp_gender { get; set; }
	public Nullable<int> noOfDependants { get; set; }
	public Nullable<decimal> Additions { get; set; }
	public Nullable<decimal> ITex { get; set; }
	public Nullable<decimal> CPP { get; set; }
	public Nullable<decimal> EI { get; set; }
	public Nullable<decimal> GrossSalary { get; set; }
}

}

// Index.cshtml from MVC

@model IEnumerable<WebAppMvc.Models.MvcEmployee>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<table class="table table-striped">
    <thead class="table-heading">
        <tr>

            <th>
                @Html.DisplayNameFor(model => model.emp_name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.emp_email)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.emp_gender)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.noOfDependants)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Additions)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ITex)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CPP)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EI)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.GrossSalary)
            </th>
            <th>Actions</th>

        </tr>
    </thead>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.emp_name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.emp_email)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.emp_gender)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.noOfDependants)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Additions)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ITex)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CPP)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EI)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.GrossSalary)
            </td>

        </tr>

    }
</table>
type here
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,280 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,288 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
300 questions
{count} votes

Accepted answer
  1. Lan Huang-MSFT 25,866 Reputation points Microsoft Vendor
    2023-06-07T07:03:12.35+00:00

    Hi @Amritpal Singh,

    First run WebAPI: http://localhost:52541/api/Employee should report an error:

    The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'

    So doing a get request on the MVC side will report Unsupported Media Type Exception.

    Add this code to global.asax below on Application_Start:

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
                GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
    

    User's image

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful