我是新人,正在学习 Web API。
这是一个示例 API,提供对图书数据库的访问。
有 2 个示例 API 操作可用于 2 个数据库,例如 ABC 和 XYZ。
/api/{abc or xyz}/books
这将返回可用的书籍。
/api/{abc or xyz}/book/{ID}
这将返回单本书的详细信息
要访问此 API,您需要 API 令牌。
就像任何现实世界的 API 一样,这些有时可能会很不稳定。
我想构建一个网络应用程序,让客户能够以 C# 语言从这两家提供商那里获得最便宜的书籍价格。
向您提供的 API 令牌不应公开。 在标头中提供以下令牌以访问 API:
x-access-token: xxxxxxxxxxxxxxxxxxxxxx
我创建了一个控制器:
public class MoviesController : ApiController
{
Movies[] movies = new Movies[]
{
new Movies { Id = 1, Name = "Star Wars", Category = "Action", Price = 1 },
new Movies { Id = 2, Name = "Spiderman", Category = "Action", Price = 3.75M },
new Movies { Id = 3, Name = "Bridget Bones", Category = "Comedy", Price = 16.99M }
};
public IEnumerable<Movies> GetAllProducts()
{
return movies;
}
public IHttpActionResult GetProduct(int id)
{
var movie = movies.FirstOrDefault((p) => p.Id == id);
if (movie == null)
{
return NotFound();
}
return Ok(movie);
}
}
模型课程
public class Movies
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
我的观点是:
<body>
<div>
<h2>All Movies</h2>
<ul id="movies" />
</div>
<div>
<h2>Search by ID</h2>
<input type="text" id="movieId" size="5" />
<input type="button" value="Search" onclick="find();" />
<p id="movie" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js">/script>
<script>
var uri = 'api/movies';
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#movies'));
});
});
});
function formatItem(item) {
return item.Name + ': $' + item.Price;
}
function find() {
var id = $('#movieId').val();
$.getJSON(uri + '/' + id)
.done(function (data) {
$('#movie').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#movie').text('Error: ' + err);
});
}
</script>
我不明白如何使用令牌身份验证。假设我想在标头中提供以下令牌来访问 API
x-access-token: xxxxxxxxxxxxxxxxxxxxxx
我该怎么做?
如有任何帮助,我们将不胜感激。