如何解决为什么LinkGenerator总是返回null?
我编写了一个类来为其他类(Aspnet core 3.1)生成链接,这些类发送带有链接的电子邮件,并通过DI获取LinkGenerator的实例。
每当我在LinkGenerator实例上调用任何方法时,它都将返回null。我在做错什么吗?
public interface IPageLinkGenerator
{
string LinkFor(string page,object values);
}
public class PageLinkGenerator : IPageLinkGenerator
{
private readonly IHttpContextAccessor _accessor;
private readonly LinkGenerator _generator;
public PageLinkGenerator(IHttpContextAccessor accessor,LinkGenerator generator)
{
_accessor = accessor;
_generator = generator;
}
public string LinkFor(string page,object values)
{
var context = _accessor.HttpContext;
var callBackLink = _generator.GetUriByPage(
context,page: page,handler: null,values: values,scheme: context.Request.Scheme,host: context.Request.Host
);
return callBackLink;
}
}
这是我来自Startup.cs的ConfigureServices方法
public void ConfigureContainer(ServiceRegistry services)
{
services.Scan(_ =>
{
_.AssemblyContainingType<IDbConnectionFactory>();
_.WithDefaultConventions();
_.ConnectImplementationsToTypesClosing(typeof(IHandle<>));
});
services.For<IConfiguration>().Use(Configuration);
services.For<IStorageClient>().Use<AzureBlobClient>();
services.AddSingleton<IHttpContextAccessor,HttpContextAccessor>();
services.AddSingleton<IDomainEventdispatcher,DomainEventdispatcher>();
services.AddSingleton<IHttpContextAccessor,HttpContextAccessor>();
services.AddScoped(typeof(IAsyncRepository<>),typeof(EfRepository<>));
services.AddScoped(typeof(IValidationRepository<>),typeof(ValidationRepository<>));
services.AddCustomisedDbContext(Configuration);
services.AddHtmlTags(new TagConventions());
services.AddMediatR(typeof(Startup));
services.For<IRazorLightEngine>()
.Use(RazorLightEngineFactory.Get())
.Singleton();
services.AddTestConfigurationInstance(_environment,Configuration);
services.AddEmailSender(_environment);
services.AddProxyHttpClient();
services.AddCustomisedIdentity(_environment,Configuration);
services.AddAuthorizationPolicies(Configuration);
services.AddCustomisedRazorPages();
services.AddWkhtmltopdf();
services.AddLocalization();
services.AddRouting();
}
public async Task Handle(BookingAdminMessageCreated @event,CancellationToken cancellationToken)
{
var url = _linkGenerator.LinkFor("/Customers/Bookings/Messages",new { Id = @event.BookingId.ToString() });
foreach (var (fullName,emailAddress) in @event.EmailDetails)
{
await _emailSender.SendAsync(emailAddress,MailType.MessageAdded,new Dictionary<string,dynamic>
{
{"FullName",fullName},{"ReferenceNumber",@event.Reference},{"BookingUrl",HtmlEncoder.Default.Encode(url)},});
}
}
解决方法
问题是我错过了页面中的页面名称。我没有指定“索引”页面。
_linkGenerator.LinkFor("/Customers/Bookings/Messages/Index" ...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。