首页 > 解决方案 > 在控制器端点内生成资源 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);
}

标签: c#.net-coreasp.net-core-webapi

解决方案


//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


推荐阅读