c# - 在控制器端点内生成资源 URL
问题描述
我想通过用资源 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);
}
解决方案
//Generates a relative URL to your current request
//E.g you are on a page in a folder named vendors that contains index.cshtml,
//create.cshtml, details.cshtml And the current request is on create.cshtml,
// the preceding code will generate a URL relative to your current url
//{"baseurl/vendors/details/556"}
var resourceUrl = Url.Page("/details", pageHandler:null,
values: new { productId = 123, otherId = 556 }, protocol: Request.Scheme);
//Used normally for MVC controllers
Url.Action("yourAction", "yourController", new { myId =455}, Request.Scheme);
//Gets the URL of the current request
Url.ActionContext()
//Generates a URL with your base URL appended to it
Url.Content("~/tyuu/you/557")
//Generates an absolute URL
Url.Link("routeName", new { myId = 456 }
//Then you can encode it this way
var encoded = HtmlEncoder.Default.Encode(resourceUrl)
将为您提供包含您想要的所有参数的 URL。
编辑
如果您认为问题出在包本身,请清理解决方案,删除所有包并dotnet restore
推荐阅读
- scala - 如何用“|”分割字符串 (管道)并将RDD转换为Dataframe
- c# - 如何在不触发无限循环的情况下编写 FileSystemWatcher
- android - APK 未安装在 OREO 中
- python - 如何从出现索引超出范围错误的列表中删除项目?
- winapi - 跨设备同步 Desktop App Converter 应用程序设置
- java - Hibernate:如何使实体和所有关联默认为只读?(或从会话中自动驱逐关联)
- bash - 用 bash 中内容的 MD5 哈希字符串替换文件的完整文件名
- openshift - 跨 openshift 集群的 pod 之间的通信
- azure-sqldw - 如何将多字节字符加载到指向 BLOB 的 SQL DW 外部表
- c - C 堆分配数组未定义行为