【发布时间】:2017-02-13 05:35:17
【问题描述】:
我是新手,正在学习网络 API
这是一个提供对图书数据库的访问的示例 API。
有 2 个示例 API 操作可用于 2 个数据库,比如 ABC 和 XYZ
/api/{abc or xyz}/books 这将返回可用的书籍
/api/{abc or xyz}/book/{ID} 返回单本书的详细信息
要访问此 API,您需要一个 API 令牌。
就像任何现实世界的 API 一样,这些 API 有时可能很脆弱
我想用 C# 构建一个 Web 应用程序,让客户可以从这两家供应商那里获得最便宜的图书价格。
提供给您的 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 我该怎么做?
任何帮助将不胜感激。 提前致谢。
【问题讨论】:
-
查看OAuth2。另外,在询问之前做一些研究。
标签: c# rest api web web-applications