简体   繁体   中英

How to use MVC custom attribute on aspx.cs page?

My application is in Asp.net MVC 4. I'm using .aspx page for opening of report. I've implemented custom user rights attribute on all action of application. I want to use it on my .aspx.cs page class or every function that is in .aspx.cs page. How to use it? can i use MVC custom attribute in aspx page In mvc I'm using like this

[AuthorizeUserControls("urlInventoryReport")]   
public ActionResult Inventory(string ReportTitle)    
{

}

How to use in .aspx.cs page

public partial class ReportViewer : System.Web.UI.Page

{

[AuthorizeUserControls("urlInventoryReport")] //it's not working

private void ViewInventoryReport()

{

}

}

Attributes are static objects that apply metadata to a type in .NET. They contain no behavior .

The reason why your attribute works in ASP.NET MVC is because MVC has a filter which runs before and after the call to the action method is performed. This filter is called by the MVC framework, which in turn is called by the route handler (a specialized HTTP handler).

The fact that the behavior is defined in the same class as the attribute (yielding an ActionFilterAttribute) is just for convenience. You could just as well separate the attribute from the action filter as is done in this answer .

Following the MVC approach to make your IActionFilter function, would be to use .NET routing for your page and make a specialized IRouteHandler that can scan your page object after it is instantiated using Reflection to determine if the attribute exists, and then execute the behavior in the associated IActionFilter . I suggest if you go this route, you analyze the MVC source code and extract the bits that you need, but it is not for the faint of heart.

Alternatively, you could put the scanning implementation into the Page_Init event, but at that point you might just be better off not bothering with declaring the attribute statically and just executing the behavior locally.

Assuming your attribute derives from ActionFilterAttribute , you could do something like:

protected void Page_Init(object sender, EventArgs e)
{
    var attribute = new AuthorizeUserControls("urlInventoryReport");
    var filterContext = CreateFakeActionExecutingContext(); // TODO: Implement this.
    attribute.OnActionExecuting(filterContext);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM