簡體   English   中英

ASP.NET 核心 Web API - 在創建實體的鏈接中包含 API 版本

[英]ASP.NET Core Web API - include API version in the links of created entity

我正在我的 WebAPI 項目中實施 HATEOAS 原則。 將任何給定類型的新實體添加到 DB 后,響應不僅應包含新創建的實體,還應包含對應 controller 中指向 GET、PUT 和 DELETE 端點的 3 個鏈接。此外,我在端點 URI 中使用 API 版本控制。

所以,我的 controller 是用屬性裝飾的:

[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
[ApiVersion("3.0")]

Startup.cs 中的 API 版本控制配置

services.AddApiVersioning(opt =>
{
    opt.AssumeDefaultVersionWhenUnspecified = true;
    opt.DefaultApiVersion = ApiVersion.Default;
    opt.ReportApiVersions = true;
});

為實體生成鏈接的方法:

public override List<ResourceUri> GetResourceUris(int id, ApiVersion apiVersion)
{
    return new List<ResourceUri>
    {
        new ResourceUri
        {
            Method = "GET",
            Uri = this._linkGenerator.GetUriByAction(
                HttpContext, 
                nameof(GetResourceById), 
                values: new
                {
                    Id = id, 
                    area = "api", 
                    version = apiVersion.ToString()
                })
        },

        new ResourceUri
        {
            Method = "PUT",
            Uri = this._linkGenerator.GetUriByAction(HttpContext, nameof(UpdateItem), values: new { id })
        },

        new ResourceUri
        {
            Method = "DELETE",
            Uri = this._linkGenerator.GetUriByAction(HttpContext, nameof(DeleteItem), values: new { id })
        },

    };
}

部分

values: new
{
    Id = id, 
    area = "api", 
    version = apiVersion.ToString()
})

取自此處,它被標記為已接受的答案。

但是,每次我發布新實體時,結果都是這樣的:

{
    "uri": "https://localhost:44386/api/v1/Resources/43?area=api&version=3",
    "method": "GET"
}

區域和版本值僅作為查詢參數包含在內,API 版本始終設置為“v1”而不是“v3”。

給予那個

AssumeDefaultVersionWhenUnspecified 

設置為 True,我使用錯誤的方式向 LinkGenerator 提供 ApiVersion。 我應該怎么做?

只需添加

[Area("api")]

轉至 Controller

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM