[英]ASP.NET Core LinkGenerator and compile time checks
ASP.NET 內核有一個有用的 class LinkGenerator 可以從 controller 方法名稱生成鏈接。 但是,這種行為似乎很脆弱,因為它依賴於僅在運行時檢查的基於字符串的合約。
如果我更改一個 controller 方法名稱或一個方法參數名稱,程序將表現不佳。 前任:
string url = _linkGenerator.GetPathByAction
(
HttpContext,
action: "GetJobStatus",
values: new { jobId = jobId }
).ToString();
你知道 ASP.NET 內核中的一個特性來強制一些編譯時間或啟動時間檢查嗎?
例如我想寫:
string url = _linkGenerator.GetPathByAction
(
HttpContext,
actionAndValues: () => this.GetJobStatus(jobId), // compile time check (method exists and arguments are compatible)
action: this.GetJobStatus, // at least this: compile time check (method exists)
).ToString();
為確保該方法存在,您可以使用nameof()
運算符:
string url = _linkGenerator.GetPathByAction
(
HttpContext,
action: nameof(GetJobStatus),
values: new { jobId = jobId }
).ToString();
據我所知,在編譯時無法確保這些值是正確的。 我不確定這是否會對您有所幫助,但有一種方法可以在運行時檢索操作描述符。 您可以在調用鏈接生成器之前使用它來檢查參數。
像這樣的東西:
public MyController(IActionDescriptorCollectionProvider actionDescriptorCollection)
{
var actionDescriptor = actionDescriptorCollection
.ActionDescriptors
.Items
.OfType<ControllerActionDescriptor>()
.SingleOrDefault(_ =>
_.ControllerName == nameof(MyController).Replace("Controller", string.Empty) &&
_.MethodInfo.Name == nameof(GetJobStatus)
);
var parameters = actionDescriptor
.Parameters
.Where(_ => _.BindingInfo.BindingSource != BindingSource.Services) // filter parameters not coming from the route
.ToList();
// do something with the parameters
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.