我正在构建一个Self Hosting Web API ...我正在尝试将记录发布到数据结构列表。
这是Markup和Jquery
<div>
Last Name:
<input id="LName"type="text" /><br />
First Name:
<input id="FName" type="text"/><br />
Gender:
<input id="Gender" type="text" /><br />
Favorite Color:
<input id="FavColor" type="text" /><br />
Date of Birth:
<input id="Dob" type="text" /><br /><br />
<button id="submit" type="submit">Submit</button>
<br /><br />
</div>
<div>
<u>Person Data</u>
<ul id="persons" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
var uri = "http://localhost:8080/api/persons";
$("#persons").hide();
getUsers();
function getUsers() {
$(document).ready(function () {
$.getJSON(uri)
.done(function (data) {
$("#persons").html("");
$.each(data, function (key, item) {
$("<li>", { html: item.lastName + " : " + item.firstName }).appendTo("#persons");
});
});
});
}
$("#submit").click(function () {
var Person = {
LastName: $("#LName").val(),
FirstName: $("#FName").val(),
Gender: $("#Gender").val(),
FavoriteColor: $("#FavColor").val(),
DateOfBirth: $("#Dob").val()
}
$.ajax({
url: uri,
type: 'POST',
ContextType: "application/json; charset=utf-8",
Accept: "application/json",
data: JSON.stringify(Person),
Success: function (data, textStatus, xhr) {
getUsers();
},
error: function (xhr, textStatus, errorThrown) {
alert("Error in Operation");
}
});
});
</script>
这是我的主持人方法:
public class Person
{
public string LastName { get; set; }
public string FirstName { get; set; }
public string Gender { get; set; }
public string FavoriteColor { get; set; }
public DateTime DateOfBirth { get; set; }
}
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class PersonsController : ApiController
{
List<Person> persons = fillPersons();
public IEnumerable<Person> Get()
{
return (persons);
}
public void Post([FromBody] Person value)
{
Person postPer = new Person();
postPer.LastName = value.LastName;
postPer.FirstName = value.FirstName;
postPer.Gender = value.Gender;
postPer.FavoriteColor = value.FavoriteColor;
postPer.DateOfBirth = Convert.ToDateTime(value.DateOfBirth);
persons.Add(postPer);
}
}
我需要了解如何纠正此错误。 Get工作正常,但Post不工作。