ActionContext gone in Microsoft.AspNetCore.Mvc.Con

2020-08-19 05:39发布

问题:

I cant find ActionContext in Microsoft.AspNetCore.Mvc.Controller

after i changed my Version to AspNetCore 1.0.0-preview1

this is Controller class (after Change):

And from "Microsoft.AspNet.Mvc" before change :

and code from old method before update :

        this.Agent = ControllerInfo.Request.Headers["User-Agent"];
        this.IP = ControllerInfo.HttpContext.Features.Get<IHttpConnectionFeature>()?.LocalIpAddress?.ToString(); 
        this.RemoteIP = ControllerInfo.HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress.ToString();
        this.Refrence = ControllerInfo.ActionContext.RouteData.Values["controller"].ToString() + "/" + ControllerInfo.ActionContext.RouteData.Values["action"].ToString();

回答1:

I replaced ActionContext with ControllerContext, and it works for me. I don't know if it's an official migration step, though.



回答2:

You can inject IActionContextAccessor to your class. It provides access to the action context.

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

Use it:

private readonly IActionContextAccessor actionContextAccessor

public FooController(IActionContextAccessor actionContextAccessor)
{
    this.actionContextAccessor = actionContextAccessor;
}

See this issue.