如何在www.example.com mvc 6中添加基本控制器asp.net

wsewodh2  于 2023-01-22  发布在  .NET
关注(0)|答案(2)|浏览(167)

我在www.example.com mvc 6中搜索了base controller,但是没有任何源代码(据我检查)。那么我如何在asp.net mvc中添加base controller,并在constuctor方法上使用服务,或者在base controller中创建新方法,或者任何想法,以便使用base controller之类的东西呢?asp.net mvc 6 however there is no any source (as far as i check).So how can i add base controller in asp.net mvc and use services on constuctor method or create new methods in base controller or any idea in order to use anything like base controller?
任何帮助都将不胜感激。
谢谢。

kknvjkwl

kknvjkwl1#

您可以通过以下方式添加基本控制器:

public class BaseController : Controller
{
    public IService Service { get; }

    public BaseController(IService service)
    {
        Service = service;
    }
}

然后,您可以创建自己的控制器并继承BaseController而不是Controller类。

public class NewController : BaseController
{
    public NewController(IService service) : base(service)
    {             
    }

    public IActionResult NewAction()
    {
        var result = Service.ServiceMethod();
    }
}
yk9xbfzb

yk9xbfzb2#

借助Microsoft.Extensions.DependencyInjection名称空间,我们可以访问以下扩展方法HttpContext.RequestServices.GetService
下面是BaseController类的源代码

public abstract class BaseController<T> : Controller where T : BaseController<T>
{
    private IService service;
    protected IService _service => telemetryInitializer ?? (telemetryInitializer = HttpContext.RequestServices.GetService<West.TelemetryService.ITelemetryHelper>());
}

OrderController类扩展此抽象BaseController

public class OrderController : BaseController<OrderController>
{
    private readonly IOrderManager _orderManager;
    public OrderController(IOrderManager orderManager)
    {
        _orderManager = orderManager;
    }
    [HttpGet]
    public string Get()
    {
        Logger.LogInformation("Hello World!");
        return "Inside the Get method of OrderController";
    }
}

相关问题