【问题标题】:generate resource URL within controller endpoint在控制器端点内生成资源 URL
【发布时间】: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


【解决方案1】:
//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

【讨论】:

  • 感谢您的回复。我调试了这些方法,这是hatebin.com/dqwhyqyncu 的结果,所以我认为问题是另一个问题。这是一个新鲜的项目,控制器继承自ControllerBase
  • 感谢您的编辑。我找到了解决方案并回答了我自己的问题。但也许你知道如何避免命名方法,因为这似乎是多余的。
【解决方案2】:

Url.Link 在使用 Name 属性标记资源方法时对我有用。所以在调用Url.Link(nameof(GetVendorById), new { id = 1 }); 时,我必须确保GetVendorById 方法的名称是这样的

[HttpGet("{id:int}", Name = "GetVendorById")]
public async Task<ActionResult<VendorResponseModel>> GetVendorById([FromRoute] int id)
{
    // ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-25
    • 2018-07-12
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 2011-11-16
    相关资源
    最近更新 更多