【发布时间】:2015-11-08 01:33:46
【问题描述】:
情况如下:
旧版 ASP.NET 产品。许多旧的 ASMX 服务(在其他类型的端点中 - ASPX、ASHX 等)。
我们正在增强一些安全逻辑。部分更改要求定义每个 ASMX 服务所属的应用程序模块。为此,我们计划使用如下所示的自定义属性。
[AttributeUsage(AttributeTargets.Class)]
public class ModuleAssignmentAttribute : Attribute
{
public Module[] Modules { get; set; }
public ModuleAssignmentAttribute(params Module[] modules)
{
Modules = modules;
}
}
以下是如何将模块应用于 ASMX 服务的示例。
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ModuleAssignment(Module.ApplicationModuleA)]
public class SomeService : System.Web.Services.WebService
{
[WebMethod(true)]
public string GetValue()
{
return "Some Service Value";
}
}
下面的 HTTP 模块将用于授权访问服务。
公共类 MyAuthorizationModule : IHttpModule { 公共无效处置() { //这里清理代码。 }
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(OnAuthorizeRequest);
}
public void OnAuthorizeRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Handler == null) return;
Attribute att = Attribute.GetCustomAttribute(HttpContext.Current.Handler.GetType(), typeof(ModuleAssignmentAttribute));
if (att != null)
{
Module[] modules = ((ModuleAssignmentAttribute)att).Modules;
// Simulate getting the user's active role ID
int roleId = 1;
// Simulate performing an authz check
AuthorizationAgent agent = new AuthorizationAgent();
bool authorized = agent.AuthorizeRequest(roleId, modules);
if (!authorized)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.StatusCode = 401;
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
}
问题在于,对于 ASMX Web 服务,HTTP 模块中的以下代码行返回 null(请注意,这适用于 ASPX 页面)。
Attribute att = Attribute.GetCustomAttribute(HttpContext.Current.Handler.GetType(), typeof(ModuleAssignmentAttribute));
这种情况下HttpContext.Current.Handler.GetType()的值为“System.Web.Script.Services.ScriptHandlerFactory+HandlerWrapperWithSession”。该类型显然不知道在 ASMX 服务上定义的自定义属性。
关于在这种情况下如何从 ASMX 服务类型获取自定义属性的任何想法?
【问题讨论】:
-
HttpContext.Current.Handler.GetType()的值是多少? -
@Mason -System.Web.Script.Services.ScriptHandlerFactory+HandlerWrapperWithSession
-
我认为这是你的问题。处理程序不是您期望的
SomeService类。它正在检索的类没有该属性 不幸的是,我不知道是否有可靠的方法可以从该上下文中获取 ASMX 类。您可以通过检查 URL 或路由来做到这一点。如果可以的话,将所有 ASMX 转换为 ASHX 可能会更容易。 -
@Mason - 不幸的是,这不是一个可行的解决方案。有 70 多种服务/1000 多种网络方法。
-
你有路由吗?还是像
~/SomeService.asmx/GetValue这样的简单URL?您可能可以使用 URL 来确定要实例化哪个服务类并从中获取属性。
标签: asp.net asmx httpmodule