【发布时间】:2020-06-01 13:52:29
【问题描述】:
我想通过将有关子资源的信息替换为资源 URL 来最小化我的 API 响应正文。因此,假设您要获取一个供应商并且不想列出他销售的所有产品,但您想提供一个指向这些信息的 URL。
例如,我在我的控制器端点中尝试过这个
string resourceUrl = Url.Link(nameof(GetVendorById), new { id = 1 });
并期望得到以下字符串
https://localhost:5001/vendors/1
不幸的是,字符串返回null。那么如何生成这样的资源url呢?
以下虚拟代码只是我想要实现的示例,我知道在获取供应商时我不应该返回供应商产品。
[HttpGet("{id:int}")]
public async Task<ActionResult<VendorResponseModel>> GetVendorById([FromRoute] int id)
{
VendorResponseModel vendor = new VendorResponseModel()
{
Id = id,
Name = "Vendor " + id,
Products = new List<VendorProductResponseModel>()
{
new VendorProductResponseModel()
{
Id = 1,
ResourceUrl = Url.Link(nameof(ProductsController.GetProductById), new { id = 1 })
}
}
};
return Ok(vendor);
}
【问题讨论】:
-
您是否尝试链接到同一个控制器中的操作?
-
有时不是,如我添加的代码示例所示:)
标签: c# .net-core asp.net-core-webapi