9th use the Filter feature

Source: Internet
Author: User
Tags visual studio 2010

2010.9.9 su Peng

Content

-Basic Filter usage

-Custom development Filter

 

Prerequisites

-Install Visual Studio 2010 Express

-Understand ASP. Net

-Understand the basic concepts of the Design Mode

 

Filter

-Additional description of Action

 

Filter in ASP. Net MVC

-Authorize

ASP. Net also has authorization management. It uses Membership to bind the Url of each file. Here, the MVC Authorization requires the user name and password before the Action access, proving that you have the corresponding operation Permissions

-HandleError

An exception is thrown in the Action, and HandleError can be processed after it is added.

-OutputCache

Cached output content

-RequireHttps

This is authorization, but the requirements are more strict. Many requests transmitted over the network are Http, that is, Hypertext Transfer Protocol, which transmits plain text, at most, it uses Encode to escape some characters and does not encrypt the data. This is very insecure. Now the Sniffer technology of the network is very popular. Anyone who puts a listener on the bridge can hear your corresponding traffic. If you analyze the traffic, you can see the content in the traffic. Therefore, for some networks with high security requirements, such as network banking, all are transmitted over Https. s means the transmission is on the SSL layer, and the SSL layer is an encryption protocol for transmission, it ensures that, during the transmission process, both parties use a confidentiality mechanism for transmission, instead of being monitored by a third party. Even if the monitoring is received, the analysis is not clear, and all the information is garbled. Therefore, Https effectively prevents data transmission from being monitored. The RequireHttps tag will require you. Once this tag is used, data transmission must be performed over Https. If it is Http, there will be some processing policies.

 

Authorize

-AuthorizeAttribute label

In the ASP. Net 2.0 era, to allow users to use roles and permission management, Microsoft provides a framework for user roles and permission management, namely, Membership. This core part has several components. The first part has a large number of Membership-related controls that can help you create users, log on to users, and display the user logon status. In the second part, there are a bunch of Service APIs that belong to the Membership namespace. It can create users, check whether users log on, and verify whether users belong to a certain permission. At the bottom layer, there is a database with five tables, including the role Roles (each different role Accesses Different folders) and the User Users (each Users belongs to one role, users has logon information). These five tables store permission management data. This Service can still be used in today's MVC Architecture. This is today's AuthorizeAttribute tag. The Roles in the label is the name of the role to verify login. In this example, the table name can be accessed only by users named Admins and SuperAdmins. For user name verification, you can write Users = "XXX, XXX" (separated by commas ). Only the attribute of the specified name can be accessed.

This is different from the Membership usage of ASP. Net WebForm in the past. If only Admin users can operate some pages, create a folder named Admin and put all user operation files under the Admin folder. When users want to access these files, they must pass the permission identification. The rule for each folder is written in Webconfig.

This policy cannot be reused in the MVC Architecture. Why? Think about the basic concepts of the MVC Architecture. Each request is no longer

A file corresponds to an Action. This makes it inappropriate to specify the file in a folder. Therefore, for different users, we only need to restrict and manage their operations. The minimum granularity of this operation is a function, that is, Action. In this way, the permissions are linked to user operations, instead of files, but are more effective.

In the preceding example, if you want to use the DeleteAllUsers method, you must first have the Admins or SuoerAdmins role, use the AdminController permission, and then use a user named Phil to access this Action. This logical relationship is actually a superimposed logical relationship.

If only the Authorize label is written and no subsequent conditions are written, it means that this is only logon authorization, and the user can access the Action as long as they log on. If you do not log on to the method with the authorization label, a 401 error will be returned, which means that the resources you access are unauthorized in IIS. Of course, like ASP. Net WebForm, unauthorized situations in the MVC Architecture can also redirect users to a login page.

 

RequireHttps

The request must be Https. It can be placed on either the Controller or the Action. When the Action of the RequireHttps tag is accessed, SSL must be used for resolution. If there is a request that is not sent using SSL, it should be discussed in detail, for a Get request, the Protocol is automatically changed to Https and then accessed. Note that your Web server must also support Https. If the protocol is changed to Https but your server does not support Https, 404 error is reported. If it is a Post request, the information in the Post cannot be encrypted, so an exception is thrown.

 

OutputCache

-CacheProfile

Specify the Cache name, which can be written on the Filter or Web. config. You can reuse the OutputCache rules on Web. config.

-Duration

Cache release time, in seconds

-Location

The default value is Any.

-NoStore

Indicates that no result is cached.

-SqlDependency

The specified cache is cached based on the value of a table specified by an SQL Server. When the value changes, the cache is released. When the value does not change, the cache is always cached.

-VaryByContentEncoding

It is a comma-separated string that describes the encoding format used by the cache.

-VaryByCustom

Whether the cache is used depends on the call to the GetValueByCustomString function. This function is in Global. asax. cs. You can reload its GetValueByCustomString function here to customize the cache.

-VaryHeader

It depends on the Http request information for cache release. You can request the same Action in different ways to release the cache.

-VaryByParam

Release cache based on parameters

After the OutputCache mark is written on the Action, when the request is sent to the Controller and the Controller executes the ActionInvoker to find the Action, it says: You are ready to work! Action says I don't have to do it. You see I have an OutputCache mark. The release time hasn't arrived yet. You can go to the View layer and simply put the cache results back and finish the operation. This avoids extra performance overhead.

 

Configuration of OutputCache in Web. config

 

Exception Filter

It specifies an Action to handle your exceptions and specifies a View to display your exceptions.

If there is no Handle exception, you cannot return the result to the user through the view correctly, and many strange things will happen, for example, an error will be reported when a line is run, the error source and information are unknown.

It should be noted that the definition of exception capture needs to be written from small to large, and you need to write down every detail. They are called in the order of Order1 and Order2. The Order of Order calls is unknown, not who writes the Order above and calls it first. We should try to write the large exception Order back.

The Filter does not catch this exception when the default Debug is run. This label does not work if an exception occurs in the Debug mode and is directly thrown to the compiler.

 

Custom Filters

To write a custom Filter, first inherit from the FilterAttribute class, and then implement one of the above four interfaces. Among them, ActionFilter and ResultFilter are the most commonly used. One is to perform operations before the Action is executed, and the other is to perform operations before the Action is returned.

 

ActionFilterAttribute

 

ActionExecutingContext

It has two parameters:

-ActionParameters

It is a dictionary class and is mainly used to pass parameters to actions.

-Result

When the current request is canceled, the Filter will generate an ActionResult to replace the result passed from the Action and send it to the user.

 

ActionExecutedContext

It has four attributes:

-Canceled

It is a Boolean value. If it is set to True, the Action request is canceled, and a Result is constructed directly to return the Result in ActionExecutedContext.

-Exception

It is supported to throw exceptions.

-ExceptionHandled

It is a Boolean value and can be set to True to cancel the returned Result. Once it is set to True, an exception is thrown, and all actions cannot get this ActionResult, and this Result will be lost forever.

-Result

Action returned results

 

ResultExecutingContext

-Cancel

-Result

 

ResultExecutedContext

-Canceled

-Exception

-ExceptionHandled

-Result

 

Write ActionFilter

Here, StopWatch stores ViewData instead of global variables because global variables have a certain impact on performance. It is better to hand over the data to the Action, because the Controller will give the data to the Action anyway.

 

Filter execution sequence

-1. Execute a small Order first.

-2. For values with the same Order, see the defined range.

-3. Final execution without Order

-4. Execute the Filter defined in the code first.

-5. The execution sequence cannot be determined for filters of the same type.

 

Summary

-Basic Filter usage

-Custom development Filter

2010.10.2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.