我在 Web API 基本控制器中有一个通用方法,我将一个 Func 传递给该方法,如果可能的话,我想以某种方式捕获 lambda 中使用的回调方法的参数...
为了说明看下面的代码
public class StuffController : BaseController
{
// method #1
[HttpGet]
public async Task<HttpResponseMessage> GetWidget(int id)
{
return await ProcessRestCall(async rc => await rc.GetWidgetAsync(id));
}
// method #2
[HttpGet]
public async Task<HttpResponseMessage> GetWidget(int year, int periodId, int modelId, int sequenceId)
{
return await ProcessRestCall(async rc => await rc.GetWidgetAsync(year, periodId, modelId, sequenceId));
}
// method #3
[HttpGet]
public async Task<HttpResponseMessage> DecodeWidget(string sid)
{
return await ProcessRestCall(async rc => await rc.GetIdsAsync(sid));
}
}
public class BaseController : ApiController
{
[NonAction]
protected async Task<HttpResponseMessage> ProcessRestCall<T>(Func<RestClient, Task<T>> restClientCallback) where T : class
{
// stuff happens...
// TODO: here I'd like to capture parameters (and their types) of the await methods passed to restClientCallback via lambdas...
// for example, in case of method #2 I would get params object [] containing year, periodId, modelId, sequenceId
T result = await restClientCallback(restClient);
// more stuff...
var response = Request.CreateResponse(HttpStatusCode.OK, result);
return response;
}
}
更新(“为什么要这样做?”)
上面的ProcessRestCall
方法做了很多事情,但主要是登录、获取数据、注销……我有一个简单的小内存缓存,我想在登录后使用它来返回数据并提高性能。我无法控制“休息客户端”及其行为方式。我的 WidgetCache 包装 System.Runtime.Caching.MemoryCache 并使用“typeof(T)-id(-id)*”作为字符串缓存键。要生成缓存键,我需要结果类型(我有)和 1 个或多个相关 ID(在 labbda 回调中作为参数传递)
可能的解决方法(也许更清洁的方法)
我可以捕获这些数据并将其作为参数发送到ProcessRestCall
public async Task<HttpResponseMessage> GetWidget(int id)
{
var cacheKey = Cache.GenerateKeyFor(typeof(Widget), id);
return await ProcessRestCall(async rc => await rc.GetWidgetAsync(id), cacheKey);
}