1.創建web API項目
QQ截圖20170316105302.png
2.創建項目
QQ截圖20170316105138.png
創建好的類視圖
QQ截圖20170316105211.png
3.添加模型
QQ截圖20170316105513.png
QQ截圖20170316105543.png
在model中添加代碼
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
4.添加控制器
添加前
QQ截圖20170316105841.png
添加
QQ截圖20170316105945.png
QQ截圖20170316105925.png
添加后
QQ截圖20170316105954.png
添加代碼:
public class PersonController : ApiController
{
Person[] persons = new Person[]
{
new Person{Id = 1,Name = "jim",Age = 20,City = "bei jing"},
new Person{Id = 2,Name = "lili",Age = 23,City = "shang hai"},
new Person{Id = 3,Name = "alan",Age = 26,City = "tian jin"}
};
public IEnumerable<Person> GetAllPersons()
{
return persons;
}
public Person getPersonById(int id)
{
var person = persons.FirstOrDefault((p) => p.Id == id);
if (person == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return person;
}
public IEnumerable<Person> GetPersonsByCity(string city)
{
return persons.Where((p) => string.Equals(p.City, city,
StringComparison.OrdinalIgnoreCase));
}
}
5.運行首頁
QQ截圖20170316110444.png
6.瀏覽器調用API
網址改為:
http://localhost:12095/api/person/
結果為
6{9L%0HE(4SRE81J}DR%PO0.png
網址變為
http://localhost:12095/api/person/1
結果為
QQ圖片20170316111710.png
7.打開Index.cshtml將所有代碼替換為
<!DOCTYPE html>
<html lang="en">
<head>
<title>ASP.NET Web API</title>
<link rel="stylesheet" />
<script src="http://www.cnblogs.com/Scripts/jquery-1.7.1.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
// Send an AJAX request
$.getJSON("api/persons/",
function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, val) {
// Format the text to display.
var str = val.Name + ': $' + val.City;
// Add a list item for the product.
$('<li/>', { text: str })
.appendTo($('#persons'));
});
});
});
function find() {
var id = $('#personId').val();
$.getJSON("api/persons/" + id,
function (data) {
var str = data.Name + ': $' + data.City;
$('#person').text(str);
})
.fail(
function (jqXHR, textStatus, err) {
$('#person').text('Error: ' + err);
});
}
</script>
</head>
<body id="body">
<div class="main-content">
<div>
<h1>All Persons</h1>
<ul id="persons" />
</div>
<div>
<label for="personId">ID:</label>
<input type="text" id="personId" size="5" />
<input type="button" value="Search" onclick="find();" />
<p id="person" />
</div>
</div>
</body>
</html>
再次運行,頁面變為:
![SC51F2}}RQ`WCZPJMTA{QG.png
5UBM_CL515JYBRKBUQWE819.png
結果應該是顯示所有Person和搜索結果,但是有些問題數據沒有顯示出來。