【发布时间】:2020-01-09 07:55:11
【问题描述】:
我正在使用 Web API 和 ASP.NET MVC 一起创建一个 ASP.NET MVC Web 应用程序。我收到此错误:
没有 MediaTypeFormatter 可用于从媒体类型为“text/html”的内容中读取类型为“IEnumerable`1”的对象
studentController (mvcproject)
namespace Mvcproj.Controllers
{
public class studentController : Controller
{
public static HttpClient client = new HttpClient();
// GET: Employes
public ActionResult Index()
{
client.BaseAddress = new Uri("http://localhost:1747/api");
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
IEnumerable<studmodel> emplist;
HttpResponseMessage response = client.GetAsync("studen").Result;
Response.ContentType = "application/json";
emplist = response.Content.ReadAsAsync<IEnumerable<studmodel>>().Result; //here get an error
response.EnsureSuccessStatusCode();
return View(emplist);
}
}
}
索引.cshtml
@model IEnumerable<Mvcproj.Models.studmodel>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.studid)
</th>
<th>
@Html.DisplayNameFor(model => model.username)
</th>
<th>
@Html.DisplayNameFor(model => model.password)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.studid)
</td>
<td>
@Html.DisplayFor(modelItem => item.username)
</td>
<td>
@Html.DisplayFor(modelItem => item.password)
</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>
输出:
http://localhost:1785/studen/index
studentController(API 项目)
namespace WebsApi.Controllers
{
public class studentController : ApiController
{
private studangEntities db = new studangEntities();
// GET: api/studen
public IQueryable<student> Getstudents()
{
return db.students;
}
// GET: api/studen/5
[ResponseType(typeof(student))]
public IHttpActionResult Getstudent(int id)
{
student student = db.students.Find(id);
if (student == null)
{
return NotFound();
}
return Ok(student);
}
}
}
输出:
http://localhost:1747/api/studen
<ArrayOfstudent xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebsApi.Models">
<student>
<password>admin@123</password>
<studid>1017</studid>
<username>admin</username>
</student>
<student>
<password>devis</password>
<studid>1025</studid>
<username>devis</username>
</student>
我也更改了application/xml - 但这导致了同样的错误。
当我调试时:
content {System.Net.Http.StreamContent}
status code System.Net.HttpStatusCode.NotFound
requestmessage {Method: GET, RequestUri: 'http://localhost:1747/studen', Version: 1.1, Content: <null>, Headers:
{
Accept: text/json
}}
我指的是这篇文章:https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/media-formatters 但错误没有解决
如何解决这个错误??
【问题讨论】:
标签: c# asp.net-web-api