如何从ASP.NET Core MVC中的另一个控制器访问GET方法? [英] How to access GET method from another controller in asp.net core mvc?

查看:400
本文介绍了如何从ASP.NET Core MVC中的另一个控制器访问GET方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个控制器:OcorrenciasAPI和IgnicoesAPI.我需要通过OcorrenciasAPI控制器通过IgnicoesAPI控制器访问GET方法.最好的方法是什么?

I have two controllers: OcorrenciasAPI and IgnicoesAPI . I need to access the GET method in my controller IgnicoesAPI trough OcorrenciasAPI controller. What's the best approach to do this?

推荐答案

使用共享功能创建一个新类,将其作为服务添加到您的startup.cs中,然后将其注入到控制器中.

Create a new class with the shared functionality, add it as a service in your startup.cs and then inject it into your controllers.

public interface IMyService
{
    string MyMethod();
}

public class MyService : IMyService
{
    public string MyMethod()
    {
        throw new NotImplementedException();
    }
}

Startup.cs

services.AddTransient<IMyService, MyService>();

OcorrenciasAPI构造函数

  private readonly IMyService _myService;

    public OcorrenciasAPI (IMyService  myService)
    {
       _myService = myService
    }

IgnicoesAPI构造函数

  private readonly IMyService _myService;

    public IgnicoesAPI(IMyService  myService)
    {
       _myService = myService
    }

使用

var result = _myService.MyMethod();

这篇关于如何从ASP.NET Core MVC中的另一个控制器访问GET方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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