Bul*_*nes 6 c# rest asp.net-web-api
我想实现支持资源扩展的RESTful服务,以便服务是自包含的,但如果客户想要限制它们所做的服务调用的数量,他们可以通过查询字符串参数来实现.资源扩展的一些示例是:
假设我有2个服务,每个服务都在自己的CSPROJ中:
ACME.AuthorsService的控制器有一个按ID获取作者的方法:
// GET /api/author/1
public async Task<HttpResponseMessage> Get(int id)
{
Author author = await _authorRepo.GetById(id);
if (author == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.OK, author);
}
Run Code Online (Sandbox Code Playgroud)
这将返回有关作者的信息:
{
"Name": "Alan Moore",
"Href": "https://acme.org/api/author/1",
"Books": [
{
"Id": 9999,
"Title": "V for Vendetta",
"Href": "https://acme.org/api/book/9999"
},
{
"Id": 8888,
"Title": "Neonomicon",
"Href": "https://acme.org/api/book/8888"
}
]
}
Run Code Online (Sandbox Code Playgroud)
同样,ACME.BooksService的控制器有一个按ID获取书籍的方法:
// GET /api/book/1
public async Task<HttpResponseMessage> Get(int id)
{
Book book = await _bookRepo.GetById(id);
if (book == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.OK, book);
}
Run Code Online (Sandbox Code Playgroud)
这将返回有关书籍的详细信息:
{
"Id": 9999,
"Title": "V for Vendetta",
"ISBN-10": "140120841X"
"ISBN-13": "978-1401208417",
"Pages": 296,
"Href": "https://acme.org/api/book/9999"
}
Run Code Online (Sandbox Code Playgroud)
使用资源扩展,客户端应该能够请求具有"Href"属性的给定字段应该扩展其结果.例如,请求https://acme.org/api/author/1?expand=books应该产生:
{
"Id": 1,
"Name": "Alan Moore",
"Href": "https://acme.org/api/author/1",
"Books": [
{
"Id": 9999,
"Title": "V for Vendetta",
"ISBN-10": "140120841X"
"ISBN-13": "978-1401208417",
"Pages": 296,
"Href": "https://acme.org/api/book/9999"
},
{
"Id": 8888,
"Title": "Neonomicon",
"ISBN-10": "1592911315",
"ISBN-13": "978-1592911318",
"Pages": 176,
"Href": "https://acme.org/api/book/8888"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我试图在ASP.NET Web API中考虑实现资源扩展的一些策略/模式,以至于任何服务(ACME.AuthorsService,ACME.BooksService等)都可以根据其扩展项目.名称和"Href"属性的可用性.
因此,在上面的示例中,当检测到扩展查询字符串属性时,将检索要展开的属性的名称(例如:books),并返回带有Books集合属性的Author模型,最好是:
当然,解决方案不应与作者和书籍相结合.处理"Href"属性可用的任何类型的资源扩展方案应该是常见的.
| 归档时间: |
|
| 查看次数: |
868 次 |
| 最近记录: |