Нет MediaTypeFormatter для чтения объекта типа 'IEnumerable`1' из содержимого с типом носителя 'text / html в asp. net mvc webapi. - PullRequest
0 голосов
/ 09 января 2020

Я создаю ASP. NET MVC веб-приложение, используя Web API и ASP. NET MVC вместе. Я получаю эту ошибку:

Нет MediaTypeFormatter для чтения объекта типа 'IEnumerable`1' из содержимого с типом носителя 'text / html

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

Index.cs html

@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 / студент / индекс

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 но ошибка не решена

как решить эту ошибку ??

1 Ответ

0 голосов
/ 09 января 2020

Как вы можете видеть здесь

requestmessage {Method: GET, RequestUri: 'http://localhost:1747/studen', Version: 1.1, Content: , Headers: { Accept: text/json }}

URI запроса http://localhost:1747/studen, но вам нужно http://localhost:1747/api/studen

Добавить / в конце базового URI

client.BaseAddress = new Uri("http://localhost:1747/api/");
...