我试图通过ASP.NET Core Essentials一书中的示例来解决这个问题,并且我得到了一个不容错误的错误(包括邮递员测试)
这是模型:
namespace PatientRecordsApi.Models
{
public class Patient
{
public int Id { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string SocialSecurityNumber { get; set; }
}
}

这是控制器:
using Microsoft.AspNetCore.Mvc;
using PatientRecordsApi.Models;
namespace PatientRecordsApi.Controllers
{
[Route("api/[controller]")]
public class PatientController : Controller
{
Patient[] patients = new Patient[]
{
new Patient
{
Id = 1,
FirstName = "John",
LastName = "Smith",
SocialSecurityNumber = "123550001"
},
new Patient
{
Id = 2,
FirstName = "Jane",
LastName = "Doe",
SocialSecurityNumber = "123550002"
},
new Patient
{
Id = 3,
FirstName = "Lisa",
LastName = "Smith",
SocialSecurityNumber = "123550003"
}
};
// GET: api/patient
[HttpGet]
public IEnumerable<Patient> Get()
{
return patients;
}
// GET api/patient/5
[HttpGet("{id}")]
public Patient Get(int id)
{
var patient = patients.FirstOrDefault((p) => p.Id == id);
if (patient == null)
{
return null;
}
return patient;
}
}
}
&#13;
这是客户:
<body>
<div>
<h2>Patient Records</h2>
<ul id="patients"></ul>
</div>
<div>
<h2>Find Patient By ID</h2>
<input type="text" id="patientId" size="5" />
<input type="button" value="Search" onclick="find();" />
<p id="patient" />
</div>
<script src="lib/jquery/dist/jquery.js"></script>
<script>
var uri = 'api/Patient';
debugger;
$(document).ready(function () {
var jqxhr = $.getJSON(uri)
.done(function (data) {
$.each(data, function (key, patient) {
$('<li>', {
text: formatPatientInfo(patient)
}).appendTo($('#patients'));
});
}).fail(function () { alert(jqxhr.error) })
.always(function () { alert("always") });
});
function formatPatientInfo(patient) {
if (patient && patient.lastName)
return patient.lastName +
', ' + patient.firstName +
': ' + patient.socialSecurityNumber;
else
return 'No patient information found.';
}
function find() {
var id = $('#patientId').val();
$.getJSON(uri + '/' + id)
.done(function (data) {
$('#patient').text(formatPatientInfo(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#patient').text('Error: ' + err);
});
}
</script>
</body>
&#13;
在客户端上运行调试器会显示&#34;数据未定义&#34;。我猜测正在返回的患者模型中的数据不是正确的json格式,但我不知道如何解决这个问题?或者是别的什么?感谢。