【发布时间】:2014-02-12 21:32:31
【问题描述】:
我正在为具有各种安全要求的各种客户端编写一些 api 调用的插件框架,以收集各种特定于业务的数据。所有插件都实现了IApiServiceEntryPoint,看起来像这样:
public interface IApiServiceEntryPoint : IDisposable
{
/// <summary>
/// Gets the name of the API Plugin
/// </summary>
string Name { get; }
/// <summary>
/// Registers the assembly in the application, sets up the routes, and enables invocation of API requests
/// </summary>
void Register();
/// <summary>
/// Gets the routing namespace of the plugin
/// </summary>
string UrlNameSpace { get; }
/// <summary>
/// Validates the user is authorized to invoke the supplied method.
/// </summary>
/// <param name="methodName"></param>
bool IsAuthorized(string methodName);
/// <summary>
/// The user initiating the API call
/// </summary>
IPrincipal User { get; }
}
请注意IsAuthorized 方法。我的意图是允许插件确定特定的IPrincipal 是否被授权调用具体类中的特定方法。使用字符串是可行的,但我宁愿更具体和可重构一些;例如,使用 lambda 表达式。
目前,我可以在我的 API 控制器中执行类似的操作:
[HttpGet]
public DateTime GetSystemTimeStamp()
{
if (IsAuthorized("GetSystemTimeStamp"))
{
return DateTime.UtcNow;
}
throw new AuthorizationException();
}
我想做的是这样的:
[HttpGet]
public DateTime GetSystemTimeStamp()
{
if (IsAuthorized(me => me.GetSystemTimeStamp))
{
return DateTime.UtcNow;
}
throw new AuthorizationException();
}
如何在我的界面中声明它,以及如何在IsAuthorized 方法中提取方法的名称来检查授权?
【问题讨论】:
标签: c# reflection interface lambda delegates