[英]HttpContext.Current.Request.Url.AbsoluteUri Equivalent in ASP.Net Core MVC
I have converted below ASP.Net MVC code to ASP.Net Core MVC, but I'm getting error like我已将下面的 ASP.Net MVC 代码转换为 ASP.Net Core MVC,但出现如下错误
'HttpContext' does not contain a definition for 'Current' and no accessible extension method 'Current' accepting a first argument of type 'HttpContext' could be found (are you missing a using directive or an assembly reference?)
“HttpContext”不包含“Current”的定义,并且找不到接受“HttpContext”类型的第一个参数的可访问扩展方法“Current”(您是否缺少 using 指令或程序集引用?)
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
public class MMAPIController : ControllerBase
{
public IConfiguration _config;
public MMAPIController(IConfiguration iConfig)
{
_config = iConfig;
}
public string AbsolutePath = HttpContext.Current.Request.Url.AbsoluteUri.Replace("%20", "");
public void SuccessMessage(int personnelSK)
{
if (Logging)
SmartLogger.Info(DateTime.Now.ToString("dd/MM/yy HH:mm:ss") + " Enter API- " + AbsolutePath + " User Id- " + personnelSK);
}
}
I have added this namespace using Microsoft.AspNetCore.Http;
我
using Microsoft.AspNetCore.Http;
. .
If your code is in a controller, then it should inherit from ControllerBase so you can access the request directly as a protected property:如果您的代码在 controller 中,那么它应该从 ControllerBase 继承,以便您可以直接访问请求作为受保护的属性:
string absolutePath = Request....
If you are in another class you can access the HttpContext by injecting the IHttpContextAccessor into your constructor (as long as you are getting your class instance through DI):如果您在另一个 class 中,则可以通过将 IHttpContextAccessor 注入构造函数来访问 HttpContext(只要您通过 DI 获取 class 实例):
public class MyClass
{
private readonly IHttpContextAccessor _httpContextAccessor;
public MyClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
...
// your code
string absolutePath = _httpContextAccessor.HttpContext.Request....
}
But you will need to ensure this is registered at startup using:但是您需要确保在启动时使用以下方法注册:
services.AddHttpContextAccessor();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.