ASP.NET Core UrlHelper 及其工作原理 [英] ASP.NET Core UrlHelper and how it works
问题描述
我对 ASP.NET Core 比较陌生,现在我正在尝试了解 UrlHelper 的一般工作原理.
I'm rather new to ASP.NET Core, and right now I am trying to get a grasp on how UrlHelper works in general.
在我的控制器中,我想为同一控制器中的另一个操作创建一个绝对 URL,例如http://localhost:PORT/api/controller/action
.现在的问题是,我该怎么做?
In my controller, I want to create an absolute URL to another action in the same controller, e.g. http://localhost:PORT/api/controller/action
. The question is now, how do I do it?
我尝试了以下方法:
var urlHelper = new UrlHelper(new ActionContext());
var url = urlHelper.Action("ACTION", "CONTROLLER");
此外,像 ActionContext
这样的不同上下文是什么?
Furthermore, what are those different contexts like ActionContext
?
推荐答案
您真的不应该自己创建 UrlHelper
.很可能无论您目前处于什么环境中,都已经有一个 IUrlHelper
实例可用:
You really shouldn’t create a UrlHelper
yourself. It’s likely that whatever context you are currently in, there is already an IUrlHelper
instance available:
ControllerBase.Url代码>
控制器内部.PageModel.Url
在 Razor 视图中.ViewComponent.Url
在视图组件中.
很有可能,您只需访问 this.Url
即可获取 URL 帮助程序.
So chances are, that you can just access this.Url
to get an URL helper.
如果您发现自己处于不存在的情况,例如在实现您自己的服务时,您可以随时注入 IUrlHelperFactory
和 IActionContextAccessor
首先检索当前操作上下文,然后为其创建一个 URL 助手.
If you find yourself in a situation where that does not exist, for example when implementing your own service, then you can always inject a IUrlHelperFactory
together with the IActionContextAccessor
to first retrieve the current action context and then create an URL helper for it.
至于什么 ActionContext
是,它基本上是一个包含各种值的对象,用于标识正在处理当前请求的当前 MVC 操作上下文.因此,它包含有关实际请求、解析的控制器和操作或有关绑定模型对象的模型状态的信息.它基本上是 HttpContext
,也包含特定于 MVC 的信息.
As for what that ActionContext
is, it is basically an object that contains various values that identify the current MVC action context in which the current request is being handled. So it contains information about the actual request, the resolved controller and action, or the model state about the bound model object. It is basically an extension to the HttpContext
, also containing MVC-specific information.
如果您运行的是 ASP.NET Core 2.2 或更高版本,您还可以使用 LinkGenerator
而不是 IUrlHelper
在您的服务中,与必须通过 IUrlHelperFactory
构造帮助器.
If you are running ASP.NET Core 2.2 or later, you can also use the LinkGenerator
instead of the IUrlHelper
inside your services which gives you an easier way to generate URLs compared to having to construct the helper through the IUrlHelperFactory
.
这篇关于ASP.NET Core UrlHelper 及其工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!