【发布时间】:2019-06-15 08:32:08
【问题描述】:
我有以下来自微软的方法:
public static string GetPathByAction(this LinkGenerator generator,
HttpContext httpContext,
string action = null,
string controller = null,
object values = null,
PathString? pathBase = null,
FragmentString fragment = default(FragmentString),
LinkOptions options = null);
当我在没有最后一个参数的情况下调用此方法时,我得到了错误:
An expression tree may not contain a call or invocation that uses optional arguments
如果参数是选项,为什么会出现这样的错误?
LinkGenerator 是这个类:
https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.routing.linkgenerator?view=aspnetcore-2.2
更新
我在一个类中注入 LinkGenerator,如下所示(这段代码没有出错,因为我传递了所有参数):
public class RequestHandler : IRequestHandler<Request, Response>> {
private LinkGenerator _linkGenerator;
public RequestHandler(LinkGenerator linkGenerator) {
_linkGenerator = linkGenerator;
}
public async Task<Response> Handle(Request request, CancellationToken cancellationToken) {
List<File> files = getFiles();
// WORKS
var url = _linkGenerator.GetUriByAction(action: "GetByUserId", controller: "FileController", null, "", new HostString());
// DOES NOT WORK
var = await files
.Select(x => new Response {
Id = x.File.Id,
Url = _linkGenerator.GetUriByAction(action: "GetByUserId", controller: "FileController", null, "", new HostString())
}).ToListAsync();
// Remaining code
}
}
public class File {
public Int32 Id { get; set; }
public String Url { get; set; }
}
【问题讨论】:
-
你怎么称呼它?您可以包含该代码吗?
-
@Ben 刚刚添加了更新...
-
I am not getting an error with this code。您能否包括产生错误的代码? -
@devNull 尝试以下操作: Url = _linkGenerator.GetPathByAction("GetByUserId", "FileController", null, new PathString(), new FragmentString())
标签: c# asp.net-core