首页 > 解决方案 > LinkGenerator GetPathByPage 不返回完整的 Uri

问题描述

我在 ASP.NET Core 2.2 MVC 项目中的 EmailSender 服务中使用 LinkGenerator。它首先返回 Null 值,直到我发现我需要在定义中包含该区域。但是,Url 仍然没有提供我期望的服务器信息。

它生成的 Url 如下所示: "/Identity/Account/Login..."

我期待这个:"https://{hostName}/Identity/Account/Login..."

我的解决方法是连接 httpContextAccessor 中发布的值。但是,这似乎是胡作非为。有人可以告诉我这应该如何工作吗?

解决方法(不是很好):

var callbackUrl = $"{httpContextAccessor.HttpContext.Request.Scheme}://" +
                  $"{httpContextAccessor.HttpContext.Request.Host}" +
                  linkGenerator.GetPathByPage(httpContextAccessor.HttpContext,
                            "/Account/Login", null, new {area = "Identity", userId = user.Id});

标签: asp.net-coreasp.net-core-mvc

解决方案


按照设计linkGenerator.GetPathByPage将返回相对路径。如果您需要完整Uri包含SchemeHost那么您必须使用另一种方法GetUriByPageLinkGenerator如下所示:

var callbackUrl = linkGenerator.GetUriByPage(httpContextAccessor.HttpContext,
    "/Account/Login", null, new {area = "Identity", userId = user.Id});

推荐阅读