c# - 如何在 ashx 文件上运行自定义 System.Attribute

标签 c# asp.net attributes ashx

通常,在常见的 aspx 文件上,我可以在页面开头使用 System.Attribute,例如:

    [AuthorizePage()]
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
    }

    public class AuthorizePage : System.Attribute
    {
         public AuthorizePage()
         {
            //do some stuff to authorize
         }
    }

在页面初始化之前,属性的构造函数会运行并执行一些操作以确保用户当前已登录,否则属性构造函数会将用户重定向到登录页面。

我想在 HttpHandler(ashx 文件)上执行相同的操作,但属性从不在 ashx 页面上初始化。

[AuthorizePage()]
public class AjaxHandler : MuCustomClassBase, IHttpHandler, IReadOnlySessionState
{
     //The interface implementations and some other custom private methods
}

我对此 ashx 页面进行 AJAX 调用。这可能是属性不运行的原因吗?或者还有其他我必须知道的事情吗?

最终,我会非常高兴知道如何在 ashx 文件上运行自定义 System.Attribute?

最佳答案

假设您使用 ASP.Net 身份验证,您只需将 .ashx 添加到 web.config 中的 protected 页面列表中,IIS/ASP.Net 将处理其余的事情:

  <location path="AjaxRequests.ashx">
    <system.web>
      <authorization>
        <allow users="?" />
      </authorization>
    </system.web>
  </location>

如果您使用自建身份验证方案,则可以重写 OnProcessRequest 并在该方法中执行必要的身份验证,并根据需要进行重定向。

关于c# - 如何在 ashx 文件上运行自定义 System.Attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14200454/

相关文章:

android - 动态设置属性值

c# - 使用 Azure 存储进行 Multi-Tenancy 应用程序日志记录和跟踪

c# - 如何将 LINQ 左外连接限制为一行

c# - 如何从 ASP.NET MVC 中的相关表更新表属性

JavaScript 运行时错误 : Unable to set property

python - 替换实例方法

jquery - 使用 jQuery 将 <body id ="grid"> 更改为 <body class ="list">

c# - ASP.NET MVC 3 动态表单生成

c# - 如何在 ASP.NET MVC 3 中为填充的下拉列表创建 View 模型

c# - 如何找到字符串中所有可能的子串?