C# ASP.NET核心链接生成器和编译时检查
ASP.NET Core有一个有用的类链接生成器,可以从控制器方法名生成链接。 但是,这种行为似乎很脆弱,因为它依赖于仅在运行时检查的基于字符串的约定。C# ASP.NET核心链接生成器和编译时检查,c#,asp.net-core,C#,Asp.net Core,ASP.NET Core有一个有用的类链接生成器,可以从控制器方法名生成链接。 但是,这种行为似乎很脆弱,因为它依赖于仅在运行时检查的基于字符串的约定。 如果我更改一个控制器方法名或一个方法参数名,程序将表现不好。 例: 您知道ASP.NET Core中的一项功能可以强制执行编译时或开始时检查吗? 例如,我想写: string url = _linkGenerator.GetPathByAction ( HttpContext, actionAndValues: () =>
如果我更改一个控制器方法名或一个方法参数名,程序将表现不好。 例: 您知道ASP.NET Core中的一项功能可以强制执行编译时或开始时检查吗?
例如,我想写:
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=\u linkGenerator.GetPathByAction
(
HttpContext,
操作:nameof(GetJobStatus),
值:new{jobId=jobId}
).ToString();
据我所知,不可能在编译时确保值是正确的。我不确定这是否对您有帮助,但有一种方法可以在运行时检索操作描述符。在调用链接生成器之前,您可以使用它来检查参数
大概是这样的:
公共MyController(IActionDescriptorCollectionProvider actionDescriptorCollection)
{
var actionDescriptor=actionDescriptorCollection
.行动描述符
.项目
第()类
.SingleOrDefault(=>
_.ControllerName==nameof(MyController).Replace(“Controller”,string.Empty)&&
_.MethodInfo.Name==nameof(GetJobStatus)
);
var参数=actionDescriptor
.参数
.Where(=>u.BindingInfo.BindingSource!=BindingSource.Services)//筛选参数不是来自路由
.ToList();
//对参数做些什么
}
使用nameof是个好主意,谢谢
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();