Web API调用报错:无MediaTypeFormatter读取text/html类型IEnumerable`1对象
解决Web API调用时的
UnsupportedMediaTypeException异常 这个异常的核心原因很明确:你的MVC代码试图把HTML格式的响应内容反序列化成IEnumerable<mvcEmployeeModel>,但默认的格式化器只认JSON/XML这类数据格式,自然会报错。大概率是你的Web API返回的不是预期的JSON,而是错误页面(比如404、500的HTML页面)。下面是一步步的排查和解决方法:
1. 先确认Web API的实际返回内容
直接用浏览器或者Postman访问你的API端点(比如http://localhost:xxxx/api/Employee),看看返回的是JSON数据,还是HTML错误页面:
- 如果是HTML页面:说明API路径不对,或者API本身抛出了错误,先修复API的路由和逻辑。
- 如果是JSON但Content-Type不是
application/json:需要调整API的格式化配置。
2. 最常见的问题:API请求路径错误
默认的Web API路由是api/{controller}/{id},但你的代码里调用的是GetAsync("Employee"),少了api/前缀,导致请求走到了MVC的路由而不是Web API,返回的是MVC的404 HTML页面。
修改请求路径:
// 把 "Employee" 改成 "api/Employee" HttpResponseMessage response = GlobalVariables.WebApiClient.GetAsync("api/Employee").Result;
3. 确保Web API返回正确的JSON格式
如果API本身返回的内容没问题,但Content-Type不正确,需要在Web API的WebApiConfig.cs里配置JSON格式化:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // 路由配置 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // 强制返回JSON,移除XML格式化器 config.Formatters.Remove(config.Formatters.XmlFormatter); // 额外允许接受text/html类型的JSON(避免部分场景下Content-Type不匹配) config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); } }
4. 优化MVC调用代码(添加请求头+异步处理)
同步调用.Result容易引发死锁,而且应该明确告诉API我们只接受JSON:
public async Task<ActionResult> Index() { IEnumerable<mvcEmployeeModel> emplist = new List<mvcEmployeeModel>(); try { var request = new HttpRequestMessage(HttpMethod.Get, "api/Employee"); // 明确指定接受JSON格式 request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await GlobalVariables.WebApiClient.SendAsync(request); if (response.IsSuccessStatusCode) { emplist = await response.Content.ReadAsAsync<IEnumerable<mvcEmployeeModel>>(); } else { // 打印错误内容方便调试 var errorContent = await response.Content.ReadAsStringAsync(); System.Diagnostics.Debug.WriteLine($"API请求错误:{errorContent}"); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"调用API异常:{ex.Message}"); } return View(emplist); }
5. 额外检查点
- 确认Web API的
EmployeeController继承的是ApiController,不是MVC的Controller。 - 确认API的
Get方法标记了[HttpGet]属性,并且返回的是IEnumerable<Employee>类型的数据。
内容的提问来源于stack exchange,提问作者Vishnu nautiyal
相关产品推荐
相关产品推荐

