[英]Web api access controller method from another controller method
我有兩個不同的控制器 --> 控制器 A,控制器 B
我有不同的方法每個控制器和它們的返回值IHttpActionResult (Method A controller A ,Method B and Controller B)
如何訪問另一個控制器方法並從另一個控制器獲取其內容
控制器 B 和內部方法 B
IHttpActionResult result = ControllerA.MethodA()
我想在控制器 B 中讀取 result.content
當請求到來時,只有應該處理請求的控制器被自動實例化。 您可以手動實例化第二個控制器,但我建議將MethodA
功能移動到基本控制器類
public class BaseController : ApiController
{
// ...
public IHttpActionResult MethodA(int id)
{
var foo = repository.Get(id);
if (foo == null)
return NotFound();
return Ok(foo);
}
}
public class ControllerA : BaseController
{
//...
}
public class ControllerB : BaseController
{
public IHttpActionResult MethodB(int id)
{
var result = MethodA();
//..
}
}
或者將通用邏輯移到單獨的類(例如服務),這樣您就可以從兩個控制器調用它。
public class ControllerA : ApiController
{
private IFooService fooService;
public ControllerA(IFooService fooService)
{
this.fooService = fooService;
}
public IHttpActionResult MethodA(int id)
{
// use fooService.Method()
}
}
public class ControllerB : ApiController
{
private IFooService fooService;
public ControllerB(IFooService fooService)
{
this.fooService = fooService;
}
public IHttpActionResult MethodB(int id)
{
// use fooService.Method()
}
}
我會考慮為兩個控制器使用一個公共基類(如果你想在兩個控制器上使用一個方法)
例如
public abstract class MyBaseController
{
public void CommonMethod()
{
// Do something here
}
}
然后像使用它們一樣
public class ControllerA : MyBaseController
{
public void MethodA()
{
base.CommonMethod();
// Do something else
}
}
public class ControllerB : MyBaseController
{
public void MethodB()
{
base.CommonMethod();
// Do Something else
}
}
1)您可以在內部使用靜態類和靜態方法將其共享給其他控制器
public static class CommonMethods
{
public static string SomeMethod(string s)
{
string RetString;
...
return (RetString);
}
}
現在您可以在任何控制器中使用它
string SomeMethodResult = CommonMethods.SomeMethod("Say Hello");
2)另一種方法是創建控制器類的實例並調用實例方法:
public class V1Controller : ApiController
{
public void Put(int id, [FromBody]string value)
{
HomeController hc = new HomeController();
hc.SomeMethod();
}
}
AController aController = new AController();
var getResponse = aController.YourMethod(values);
如果您的方法返回 Json,那么您可以輕松地解決它
JavaScriptSerializer().Deserialize
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.