Is there a way to call your applications API controller from another class without using the API's url?
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");
}
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?
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”.
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();
}
}