Use Attribute In Asp.net - c#

I have something issue on how to use Attribute in asp.net page class.
The below code slice is the background:
A method is declared like below in a aspx class page:
[SomeAttribute(Name=”Test”,TargetType=typeof(System.Int32)]
Public void Verify(object obj)
{
//code to verify…
}
And other pages would use the attribute too.
Now I want a Module to do is that it will invoke a method before the Verify method is calling.
Currently, my solution is using a customer IHttpModule implement class to do it by registering the BeginRequest event.
In the method referred to the event, how can I get the method that is calling currently by request in asp.net ? This is the way I could know the request is calling Verify method so that I can do something with the Attribute on it.

I'd recommend checking out PostSharp:
http://www.sharpcrafters.com/
It's got all that goodness, and more, built in.

Related

Asp.net 4.5 Custom Attribute Webform

Using a Asp.Net old project, to access webforms I need to create a custom class Attribute that reads users rights like 'Rights.ViewDashboard' or 'Rights.CanEdit' an so. The class code is:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class AuthorizationAttribute : Attribute
{
public AuthorizationAttribute(Rights permission)
{
if (Security.IsAuthorizedTo(permission))
return;
HttpContext.Current.Server.TransferRequest("~", false);
}
}
In the aspx webform I have:
[Authorization(Rights.ViewDashboard)]
public partial class DashboardRisorse : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
When the user calls the webform if he haven't specific right the page is not loaded and site is redirected to the default page. But if he make a refresh of the page the code isn't execute, attribute is ignored and the page is loaded. When debugging I see that this attribute is executed only once.
Where is my fault?
I don't need Net Core solution because the project has old assemblies.
Thanks.
Ingd
I am assuming here that you are trying to define custom attribute similar to ActionFilter Attributes in MVC. Unfortunately ASP.Net does not work in the same way.
You have two options
Create an HttpModule and use one of the events available to build your logic
Write the logic you want to execute in Page Load. Use Page.IsPostBack to identify if it is initial load of the page or if the page is being posted back. Write the logic you need within the if.. else if conditions
In case my assumption was incorrect then please provide more details on your query specifically what is it that you are trying to achieve using the Attribute.

how can I validate this invalid property in web api?

I have a user search request object which looks like this:
UserSearchRequest
{
FirstName:"John",
LastName:"Smith",
Expand:["groups","devices"]
}
Expand is an optional parameter. I have validation which checks that the provided Expand parameters are within thin expected set of parameters. The problem is that if a client submits a request like this:
{
FirstName:"John",
LastName:"Smith",
Expand:1
}
By default Web API 2 will pass this request to the controller method with an Expand value of null. So the user won't know that he submitted a bad request and the controller won't be able to identify it as a bad request b/c null is a valid value for this property. Is there a way to override this default behavior?
Action filters are triggered before controller executes its logic. I will give a general idea of what you need to do to get you on the right track.
First requirement for ActionFilter is to create your own filter class by extending ActionFilterAttribute class.
The following is a sample for this
public class ValidateCustomModel : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
//Write your logic to check that all attributes are not null
}
}
Now onto the second step. This step will register your filter in WebApiConfig class so that the application will know that it has to pass requests to this filter wherever the attribute is used
config.Filters.Add(new ValidateModelAttribute());
Now the third step is to call the custom class as an attribute on the controller method that is being executed when user makes a request.
[ValidateModel]
Hope this helps you to customise it for your own logic. Happy coding.

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);
}

How to run a custom System.Attribute over an ashx file

Normally, on a usual aspx file, I can use System.Attribute at the begining of the page, like:
[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
}
}
And before the page initializes the Attribute's constructor runs and do some stuff to ensure a person is currently logged in, otherwise the attribute constructor Redirects user to a login page.
I wanted to do the same on a HttpHandler (ashx file), but the attribute never initializes when on a ashx page.
[AuthorizePage()]
public class AjaxHandler : MuCustomClassBase, IHttpHandler, IReadOnlySessionState
{
//The interface implementations and some other custom private methods
}
I do an AJAX Call to this ashx page. Could this be the reason why the Attribute doesn't run? Or any other things I must know?
Eventually, I would be extremely happy to know How to run a Custom System.Attribute over an ashx file?
Assuming you are using ASP.Net authentication, you can just add the .ashx to the list of protected pages in web.config and IIS/ASP.Net will take care of the rest:
<location path="AjaxRequests.ashx">
<system.web>
<authorization>
<allow users="?" />
</authorization>
</system.web>
</location>
If you are using a self-built authentication scheme, you could override OnProcessRequest and perform the necessary authentication in that method, redirecting as needed.
Attributes don't do anything by themselves. You can pile 10 random attributes on a class and nothing will really happen. Attributes just provide metadata about the class/method/property.
There should be a piece of code that looks at the metadata and act on it. Since you seem to be using custom AuthorizePageAttribute such piece of code either don't run for handlers or does not expect class that is not derived from Page to have such attribute.
To fix an issue you need to find what handles you custom attribute and fix it. You may need to add similar code to your handlers directly.
The fact that your code in constructor of attribute does something useful for a page class on every request to that page sounds suspicious - I'd expect such attributes to be created once per type instance. Relying on non-trivial code in constructor of an attribute to run per-instance of the class seems dangerous to my.
Well first of all yes you are reinventing the ActionFilterAttribute in Asp.Net MVC. But, I have to ask if you really need to use attribute? I suggest you to use inheritance model. Let me simply explain; you might have a SecurePage : Page class that implements the security operations. You may then pass the security code that is related to the derived page.
And if you insist on using attributes, you should intersect the handler mechanism by writing a base factory handler that routes to the needed handler. This handler should behave like a mediator object.

Making an Ajax call in Umbraco from inside user control

For an Umbraco project, I am trying to make a simple Ajax call.. I can't use PageMethods because I need to make the call from inside a UserControl..
I tried to do it via web service call like this:
Web service method:
[System.Web.Script.Services.ScriptService]
public class MapService : System.Web.Services.WebService
{
[WebMethod]
public static string GetCities(string ProvinceCode)
{
return "foo";
}
}
JS part in my ASCX file:
<script language="javascript" type="text/javascript">
function callServer(src) {
MapService.GetCities(src, displayMessageCallback);
}
function displayMessageCallback(result) {
fillDDL(result);
}
</script>
The problem is, "MapService.GetCities" method doesn't get invoked..
What might be the problem here?
Alternatively, what is there any better way to make these kind of Ajax calls in a User Control?
I've been usign the Umbraco base REST Extensions for this kind of thing. I think it's a lot simpler to implement and if you use a JSON Serialiser on the server you even have proper JSON objects on the client.
Use REST method for doing this. we have implemented this for our projects. For this you have to edit the restExtensions.config and add your entry.
I think the problem might be that the javascript inside the usercontrol does not communicate with the scriptmanager in the page.
I can see two ways of dealing with this.
1. Use jQuery to call the webmethod instead of asp.net ajax.
2. through the control javascript call a method in the page javascript which will call the webmethod, i.e. use the page as a proxy. This has the added advantage of enabling you to use a page method instead of a web service.

Categories

Resources