ASP. net mvc fourth Preview (Part 1)

Source: Internet
Author: User

[Original address] ASP. net mvc preview 4 release (Part 1)
[Original article publication date] Monday, July 14,200 AM

 

There are a bunch of new features and features in this new version. In fact, there are a large number of features. I decided that I needed two posts to fully discuss them, this first post will discuss the new caching, error handling, and security features in the fourth preview, as well as some test improvements, my next post will discuss the newly added Ajax features in this version.

Filter interceptors)

The action filter attribute (filter attributes) is ASP. net MVC is a very useful Extension function. This was initially added to the second preview version, allowing you to inject interception code into the MVC controller request, it can be executed before and after the Controller and Its Action method, which can lead to some very good encapsulation scenarios, in which you can use a very clean, declarations can easily encapsulate and reuse features.

The following is an extremely simple example. The scottgulog filter can be used to record the details of exceptions thrown during request execution. It is very easy to implement a custom filter class. As long as it inherits from the actionfilterattribute type and overwrites the appropriate method, before or after the Controller action method is called, or run the code before or after the actionresult is processed into the reply.

In ASP. net MVC controller is also very easy to use filters, as long as it is declared as an attribute in the Action method, or on the Controller class itself (in this case, it will be applied to all action methods in controller ):

In the above example, you can see two filters applied. I want to apply "scottgulog" to the "about" Action method, the "handleerror" filter is applied to all action methods of homecontroller.

 

ASP. previous versions of net MVC have already enabled the filter scalability, but no pre-fabricated filters have been released. The fourth version contains several useful filters that can be used to process the output cache, error Handling and security scenarios.

Outputcache Filter

[Outputcache] The filter provides a simple way to convert ASP. net MVC and ASP. net output cache function (in ASP. net MVC in the third preview version, you need to write code to achieve this function ).

To test this, modify the message value of the index Action Method in homecontroller (generated by the vs ASP. net mvc Project template) to display the current time:

Every time you refresh the page when running this application, you will see the timestamp update:

We can add the [outputcache] attribute to our action method to enable the output cache for this URL. We will use the following declaration to configure the cache to reply for 10 seconds:

Now, when you click Refresh, you will see that the timestamp is updated every 10 seconds. This is because the action method is called every 10 seconds. All requests at other times are from ASP. net output cache supply (meaning no code is run, so the request response is extremely fast ).

In addition to the time interval, the outputcache attribute also supports standard ASP. NET output cache change options (varies with parameters, header content, content encoding, and custom logic ). For example, the following example stores different page cache versions based on the value of the pageindex query string parameter, and automatically displays the correct version based on the query string value of the entered URL:

You can also combine ASP. NET database cache failure function, which allows you to automatically cause cache failure after the URL-dependent database is modified (TIPS: the best solution to achieve this function is in your web. configure a cacheprofile section in config, and configure pointing to this node in the outputcache attribute ).

Handleerror Filter

[Handleerror] The filter provides a declaration method to indicate in a controller or action method. If you are processing an ASP. if an error occurs in the. net mvc request, a friendly error response should be displayed.

To test it, add a new testcontroller in the project to implement an action method, and throw an exception as follows:

By default, if you direct the browser to this URL, it displays a default ASP. net error page (unless you go to the Web. the <mermerrors> section is configured in the config file ):

We can add a [handleerror] attribute to our controller class or the action method to change the HTML error to be displayed and display the friendly Information for end users:

The handleerror filter captures exceptions in the residence (including errors thrown when processing the view template) and displays a custom error view reply when an error occurs. By default, it tries to find a view template named "error" in your project to generate a reply. You can place the "error" view in the directory of the corresponding view of the same controller (for example, the \ views \ test directory of testcontroller above ), it can also be placed in the \ views \ shared folder (the system will first find an error view specific to the Controller, if not found, it will find in the shared folder, this folder contains views shared by all controllers ).

Starting from the fourth preview, when you create a new ASP. net mvc project, Visual Studio automatically adds a default "error" view template to the \ views \ shared folder:

After the [handleerror] attribute is added to our testcontroller class, the remote user will be displayed with an HTML error page like the following by default. (Note, it uses the project's dashboard page, so that the error information is integrated into the site ). Obviously, you can customize the error view template to display any HTML or more friendly error information you want. The following is only the original information that comes with this version:

To help developers browse applications locally, the default error view template provided by the new project template in Visual Studio also displays additional error stack trace information:

You can delete the code in the error view template to disable it, or set <mermerrors> to "off" in your web. config file ".

By default, the [handleerror] filter captures and processes all exceptions thrown in the request. You can also specify the "exceptiontype" and "View" attributes on the [handleerror] attribute to specify the specific exception type you are interested in and the custom error View:

In the above code, I chose to display the custom error view for sqlexception and nullreferenceexception exceptions. The default "error" view template will be used for all other exceptions.

Authorize Filter

[Authorize] The filter provides a declarative method to control access permissions to the Controller or action method. It allows you to indicate that the user must have logged on, or they must be a specific user or a specific security role to access. This filter can be used for any type of authentication (including windows and forms-based authentication). It also supports automatic redirection of anonymous users to logon pages.

To test this, add a [authorize] filter to the "about" Action Method in the default homecontroller in Visual Studio:

As stated above, the [authorize] attribute indicates that the user must have logged on to the website before requesting "about" action. If users who have not logged on attempt to access the/home/about URL, they will not be able to access this page. If the web application is configured to use Windows-based authentication, ASP. NET will automatically use their Windows logon identity to authenticate users. If it succeeds, it will allow them to access. If the web application is configured to use forms-based authentication, [authorize] will automatically redirect the user to the login page for authentication (then they will be able to access ):

The [authorize] attribute also allows you to grant access permissions to only specific users or roles. For example, if I want to restrict the access permission of "about" action to only myself and Bill Gates, I can write as follows:

In general, except for apps that are irrelevant, you should not hard-write user names in the Code. Generally, you should use high-level concepts like "Roles" to define permissions, then, the user is mapped to the role (for example, using the Active Directory or database to store these mappings ). The [authorize] attribute greatly facilitates access control over controllers and actions by using the "Roles" attribute:

[Authorize] attributesNoDepending on any specific user identity or role management mechanism, it only uses the "user" object of ASP. NET. This object is scalable and can be used by any identity system.

Accountcontroller class

As mentioned above, the [authorize] attribute can be used in any authentication or user identity management system. You can write or use any customized logon ui or user/password management system you want.

But to help you get started, Asp. net MVC project templates now contain a pre-fabricated "accountcontroller" class and related logon views. They implement form authentication member systems and support logon, exit, and registration of new users, change the password. All view templates and UIS can be easily customized and are implemented independently of the accountcontroller class:

The site. Master template also includes the UI in the upper right corner, which provides the login/exit function. When using form-based authentication, if you have not yet performed authentication, it will prompt you to log on:

After you pass the authentication, it displays a welcome message and an exit link:

Click the login link above to transfer the user to a login screen like the following for authentication:

New users can click the registration link to create a new account:

Error Handling and error information display are also built-in:

The accountcontroller class added to the new project uses the built-in ASP. net membership API to store and manage user creden( (the membership system uses the provisioner API to allow access to any background storage, Asp. net contains the built-in Active Directory and SQL Server Provider ). If you do not want to use the built-in membership system, you can retain the same accountcontroller Action Method signature, view template, and forms authentication ticket logic, you only need to replace the user account logic in the accountcontroller class. In the next ASP. in the. net mvc preview, we plan to encapsulate the interaction logic between the accountcontroller and the user identity system into an interface, this will further facilitate your access to your own user storage system (without having to implement a complete membership prover) and facilitate unit testing on it and accountcontroller.

Our hope is that this provides a good way to get started quickly, allowing everyone to have a working end-to-end security system after creating a new project.

Test tempdata

The last improvement mentioned in the first post of the fourth preview is some improvements made to the Controller class, which will allow you to more easily unit test the tempdata set, the tempdata attribute allows you to save data that will last for a future user request. It means that the data will only last until the next request (and will be deleted later ). It is generally used in MVC scenarios: You want to redirect a client to change the URL in the browser, and then want to save temporary data in a simple way.

In the previous ASP. net mvc preview, you need a mock object to test the tempdata set. In the fourth preview, you no longer need mock or set anything. Now you can add and verify objects directly in the tempdata set of the Controller in the unit test (for example, fill in the tempdata attribute of the controller before calling an action method, or verify that the action method has updated tempdata after the action method is returned ). The actual storage mechanism of the tempdata set is now encapsulated in a separate tempdataprovider attribute.

Conclusion

We hope that the above post content will be applied to the ASP. some new features and changes in the fourth preview of net MVC provide a brief introduction. The next post will discuss the newly added Ajax function and demonstrate how to use it.

I hope this article will help you,

Related Article

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.