ASP.NET Core UrlHelper及其工作方式 [英] ASP.NET Core UrlHelper and how it works

查看:72
本文介绍了ASP.NET Core UrlHelper及其工作方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对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 .可能无论您当前所处的上下文是什么,已经有一个

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:

因此,您可以访问 this.Url 以获得URL助手.

So chances are, that you can just access this.Url to get an URL helper.

如果您发现自己不存在这种情况,例如在实施自己的服务时,则可以随时注入 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操作上下文.因此,它包含有关实际请求,已解析的控制器和操作或有关绑定模型对象的模型状态的信息.它基本上是对

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或更高版本,则还可以使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆