Roy*_*mir 2 c# reflection asp.net-web-api
我们的系统中有很多服务.(与移动公司合并)
所以,(例如)我们有:
Action1 in Controller1
Action2 in Controller1
...
Action4 in Controller4
Action5 in Controller4
...
Run Code Online (Sandbox Code Playgroud)
目前,移动公司通过单个请求调用每个操作.
但最近他们告诉我们," 我们可以向你发送一个要调用的动作列表吗?而不是每次手动运行单个动作......? "
所以我试着反思:
ServicesController :
[HttpGet]
[AllowAnonymous]
public HttpResponseMessage AAA( )
{
Type type = typeof(UsersController);
var instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("Test2", BindingFlags.Instance | BindingFlags.Public);
var t= method.Invoke(instance, new object[] { "royi" });
return Request.CreateResponse(HttpStatusCode.OK, t);
}
Run Code Online (Sandbox Code Playgroud)
而且:
UseresController :
[HttpGet]
[AllowAnonymous]
public HttpResponseMessage Test2( string ggg)
{
return Request.CreateResponse(HttpStatusCode.OK, "hello"+ggg);
}
Run Code Online (Sandbox Code Playgroud)
当我通过提琴手跑道时:
http://es.com/api/services/aaa (GET)
它确实有效,但(显然)Request另一方面是空的:

题
如何Test2按预期运行?我正朝着正确的方向解决这个问题吗?或者webApi是否为此类内容构建了机制?
你最好用它ActionInvoker来做到这一点:
public HttpResponseMessage AAA()
{
var ctrlDesc = new HttpControllerDescriptor(this.Configuration, "UsersController", typeof(UsersController));
var actionDesc = new ReflectedHttpActionDescriptor(ctrlDesc, typeof(UsersController).GetMethod("Test2"));
var ctrlCtx = new HttpControllerContext(this.Configuration, this.Request.GetRouteData(), this.Request);
var apiCtrl = ctrlDesc.CreateController(this.Request) as ApiController;
apiCtrl.Request = this.Request;
apiCtrl.Configuration = this.Configuration;
apiCtrl.ControllerContext = ctrlCtx;
ctrlCtx.Controller = apiCtrl;
ctrlCtx.ControllerDescriptor = ctrlDesc;
ctrlCtx.Request = this.Request;
ctrlCtx.RouteData = this.Request.GetRouteData();
var actionContext = new HttpActionContext(ctrlCtx, actionDesc);
actionContext.ActionArguments.Add("ggg", "royi");
var invoker = this.Configuration.Services.GetActionInvoker();
return invoker.InvokeActionAsync(actionContext, CancellationToken.None).Result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1642 次 |
| 最近记录: |