访问内部API控制器 [英] Access internal API controller

查看:84
本文介绍了访问内部API控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以从另一个类中调用应用程序API控制器而不使用API​​的URL?

Is there a way to call your applications API controller from another class without using the API's url?

例如,我在"personContoller"中使用了此方法

For example I have this method in a "personContoller"

    public async Task<ActionResult> GetPersonRecord(string id)
    {
        Person person;
        var link = "api/entity/Person/" + id + "?format=json";
        string results = await OneIMAction(link);
        person = JsonConvert.DeserializeObject<Person>(results);
        string json = JsonConvert.SerializeObject(person, Formatting.Indented);
        return Content(json, "application/json");
    }

如何在不使用Web请求的情况下,在同一应用程序的另一个C#类中从此方法访问JSON结果?有可能吗?

How can I access the JSON result from this method in another C# class within the same application without resorting to using a web request? Is that possible?

推荐答案

根据单一职责原则"(SOLID的第一原则),每个模块或类都应对软件提供的功能的单个部分负责".

According to the Single Responsibility Principle (the first principle of S.O.L.I.D.), "every module or class should have responsibility over a single part of the functionality provided by the software".

从API控制器继承的类必须响应Web请求.如果我们希望一个API控制器可以访问另一个API控制器的某些动作,则应该创建一个Web请求并调用该URL(不建议这样做).在某些情况下,我们希望通过多种方法调用任务,则将其转移到Facade,这被称为类服务.想要使用它的API控制器的所有操作都将使用类服务.

The class which inherits from the API Controller has to respond to the web requests. If we want an API Controller has access to some action of another API Controller, we should create a web request and call that URL (which is not recommended). In cases we want a task to be called by more than one method, we transfer it to Facade which is known as a class service. And all actions of the API Controllers who want to use it, will use the class service.

public class TestService 
{
    public void Do()
    {
      // ...
    }
}


public class HomeController1 : Controller
{
    public ActionResult Index()
    {
        var service = new TestService();
        service.Do();
        return View();
    }
}


public class HomeController2 : Controller
{
    public ActionResult Index()
    {
        var service = new TestService();
        service.Do();
        return View();
    }
}

这篇关于访问内部API控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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