ASP. net mvc Note Article 2

Source: Internet
Author: User
Tags website performance

ASP. net mvc Note Article 2

I want to prepare a speech a few days ago, so I have prepared some basic MVC things. I used MVC before, But I just used it, instead of understanding it, so I took this opportunity to take a good look at other people's MVC videos (a video released by a Microsoft MVP Member, I believe some people have seen it), sort out this note, share it all at once, everything about basic MVC is introduced, but it is very basic. I was going to post an article, but I found that there were a lot of things, so I divided it into two blogs. This is the last one!

1. ASP. net mvc request process

1

2. Controller

(1) The Controller plays the role of processing client requests in ASP. net mvc.

1) The System. Web. Mvc. IController interface must be implemented.

-> Generally, the System. Web. MVC. Controller class is inherited directly.

2) It must end with a Controller.

3) process specific client requests with different actions

3. Action

(1) It means that the type of the returned value inherited from the System. Web. Mvc. Controller class can be compatible.

(2) ActionResult Method

Namespace MvcApplication. Controllers

{

Public class HomeController: Controller

{

Public ActionResult Index ()

{

ViewBag. Message = "Han Yinglong ";

Return View ();

}

}

}

(3) ActionResult of ASP. NET MVC3

    

(4) Considerations

1) the Action that can be accessed through a URL must be a Public method.

2) If the [NonAction] attribute is marked, this Action cannot be accessed through a URL.

3) by default, the method name of the Action is the name of the Action (accessed through URL). If you have special requirements, you can also mark the specific Action name through [ActionName ("OtherActionName ")].

4) We can use [HttpPost] [HttpGet] to differentiate actions with the same name for processing different request actions.

4. ASP. NET Routing and filter

(1) The responsibility of the ASP. NET Routing Module is to map incoming client (browser) requests to specific MVC Controller Actions.

(2) Routing Mechanism

1) routing engine-uring URLS to Controlller

Public static void RegisterRoutes (RouteCollection routes)

{

Routes. IgnoreRoute ("{resource}. axd/{* pathInfo }");

Routes. MapRoute (

"Default", // route name

"{Controller}/{action}/{id}", // URL with Parameters

New {controller = "Home", action = "Index", id = UrlParameter. Optional} // default value of the Parameter

);

}

Protected void Application_Start ()

{

RegisterRoutes (RouteTable. Routes );

}

2)/Products/Detail/8

Routes. MapRoute (

"Default", // route name

"{Controller}/{action}/{id}", // URL with Parameters

);

Public class ProductsController: Controller

{

Public ActionResult Details (int id)

{

Return View ();

}

Public ActionResult Edit (int id)

{

Return View ();

}

}

5. Routing change in MVC3

(1) migrating from the System. Web. Routing3.5 program to the System. Web 4 program set has become part of the basic service.

(2) In ASP. NET 4, the Routing Module is registered in the root Web. Config. You do not need to register it in Web. Config of your application.

(3) The UrlRoutingModule reduces the number of events it processes and only processes PostResolveRequestCache events.

(4) A new RequestContext attribute is added to HttpRequest.

(5) added PageRouteHandler to support WebForm routing.

(6) Four ageroute overload methods are added to RouteCollection, which makes it easier to add routing rules.

6. Benefits of Routing

(1) convenient Implementation of REST services

(2) Url friendliness, facilitating SEO and enhancing user experience

(3) The call rules of controllers and actions can be customized to reduce coupling and improve flexibility.

7. Filter

(1) Filter is an AOP mode that can interfere with a series of operations. It decouples dependencies to a large extent, making our code more concise and more functional.

(2) ASP. net mvc provides four Filter interfaces.

1) IActionFilter

2) IAuthorizationFilter

3) IExceptionFilter

4) IResultFilter

(3) ASP. net mvc provides common Filter implementations such as OutputCacheAttribute, HandlErrorAttribute, and AuthorizeAttribute.

(4) Filter Cutting Process

1) Taking ActionFilter as an Example

      

8. Filter in SP. NET MVC3

(1) provides the global Filter registration function.

(2) provides OutputCache support for ChildAction

1) combined with [ChildActionOnly]

9. Model

(1) In MVC, the Model is mainly responsible for maintaining the data status, retrieving data from the data storage and passing it to the controller. The data transmitted by the client is processed and then transmitted back to the data storage system, is a heavier layer in MVC

(2) ASP. net mvc Framework does not care about data storage systems, and simplifies the use of Model through some additional help classes and Model binding mechanisms.

1) self-binding mechanism

2) self-verification mechanism

(3) Improvement of ASP. NET MVC3 Model

1) ASP. NET MVC3 Model mainly improves the verification mechanism

-> Data Annotations)

-> Client Validation)

-> Remote verification)

-> Self Validation)

(4) data verification

1) Use the System. ComponentModel. DataAnnotations method set for verification, and have some convenience impact on client verification.

2) You can inherit ValidationAttribute to implement custom validation Attribute.

(5) Client Verification

1) Use the Jquery validation plug-in

2) jquery. validate. unobtrusive. mis. js client Verification

-> Enable client Verification

<Deleetask>

<Add key = "ClientValidationEnabled" value = "true"/>

<Add key = "UnobtrusiveJavaScriptEnabled" value = "true"/>

</AppSettings>

-> Reference JQuery

<Script src = "http://www.cnblogs.com/Scripts/jquery.validate.min.js" type = "text/javascript"> </script>

<Script src = "http://www.cnblogs.com/Scripts/jquery.validate.unobtrusive.min.js" type = "text/javascript"> </script>

-> Special Verification

@{

Html. EnableClientValidation ();

}

(6) remote verification

1) the use of the Model is similar to that of RequiredAttribute.

1) [Remote ("verified Action name", "Controller name", ErrorMessage = "error message not verified remotely")]

2) Note

1) The Action used for remote verification must be HttpGet, and the Post submission is invalid.

2) The result returned by Action is JsonResult, not a Boolean value.

(7) self-verification

1) Use ValidationContext and ValidationResult in the Model to provide verification

Public IEnumerable <ValidationResult> Validate (ValidationContext validationResult)

{

If (EndDate <= StartDate)

{

Yield return new ValidationResult ("the end time must be later than the start time ");

}

}

10. Best practices

(1) layered design

1) multiple projects

2) Separation of concerns

3) replaceable data access layer

(2) Repository mode (Business Layer)

1) encapsulate the CRUD operation to Repository.

2) business logic/data verification is encapsulated into Service

3) Controller calls Respository and Service

(3) PRG mode (method)

1) POST

2) Redirect

3) GET

4) The PRG mode is used to ensure that only one data modification occurs.

(4) minimize the amount of code in the view

1) The view does not contain the logic code for data processing.

2) Avoid containing large code blocks in a view

3) construct multiple attempted/local views

4) use the appropriate @ Helper and @ Function syntax

(5) Say "Bye bye" to the magic string"

1) ASPX Mode

@ ViewData ["Message"]

@ ViewData ["TotalCount"]

2) Razor Mode

@ Model. Message

@ Model. TotalCount

3) try to use a specific Model instead of ViewData/ViewBag.

(6) DomainModel (domain model )! = ViewModel)

1) Minimized ViewModel that meets requirements

1) valid Verification

2) High Security

3) High Performance

2) use some Mapping tools for Bidirectional ing Filling

1) AutoMapper, EmitMapper, ValueInjecter

2) custom ORM-GenerPoint.ORM

3) use special ViewModel filling logic to easily address internationalization/Localization

(7) use the new AJAX Helper

1) Web. Config Sino-German appSettings

<Add key = "UnobtrusiveJavaScriptEnabled" value = "true">

2) Reference jquery. unobtrusive-ajax.js in the view

3) call AJAX Helpers in the view

1) @ Ajax. ActionLink ("Home", "Index", new AjaxOptions {UpdateTargetId = "main "})

2) <a data-ajax = "true" data-ajax-mode = "replace" data-ajax-update = "# content" href = "/"> Home </a>

(8) try to write HTML code in the view

1) try to write pure HTML code

2) Do not intentionally customize Helper such as HTMl. Submit to hide Html.

3) Try not to use the WebForm Control for view code Rendering

(9) IIS Express 7.5

1) complete Web Server Functions

1) SSL

2) rewrite the website

3) You can perform a local test on the configuration of <System. webServer>.

4) IIS7.X other template Sets

2) Lightweight

1) <5 M

2) No administrator account is required

3) High Performance

11. Soft Power of Performance Optimization

(1) Basic knowledge about HTTP, Cache, and Ajax

(2) ability to analyze and plan the overall Web execution environment

(3) ability to design appropriate cache policies

(4) ability to further analyze website performance data

12. Hard work on Performance Optimization

(1) familiar with. net/C #/ASP. net mvc Framework and core principles

(2) be able to further properly plan projects and design separation of concerns

(3) be familiar with Profiling technology and be able to analyze performance bottlenecks

(4) code optimization for various environments to improve program execution performance

13. Key factors determining WEB Performance

(1) Web performance optimization basics-HTTP

1) http is stateless

2) A webpage contains n http requests

(2) analyze the Http status when the web page is opened

1) Fiddler

2) IE10 Developer Tools

(3) Client Optimization

1) fewer HTTP requests

2) bandwidth used for download

3) Length of DNS query

4) CSS display speed

5) JavaScript call speed

(4) server Optimization

1) IIS

-> Control the client

HTTP Cache Control

-> Control the server

Output Caching)

Improve database query speed

2) ASP. NET MVC

-> Call Performance Improvement

-> Appropriate cache policies

(5) [SeesionState]

1) Use the SessionState attribute

How to control the Controller Access phase status data (Session)

2) Note: After closing the Session, you cannot use TempData to transmit information.

(6) [OutputCache]

1) Html. Action and Html. RenderAction support Output Caching

->@{ Html. RenderAction ("ActionName ")}

-> @ Html. Action ("ActionName ")

2) ChildAction finally supports the OutputCache attribute

-> [ChildActionOnly]

-> Only Duration, VaryByCustom, and VaryByParam parameters are supported.

-> The CacheProfile parameter cannot be used.

(7) change the default ViewEngine settings

1) Remove unnecessary ViewEngine to speed up parsing View

-> ViewEngines. Engines. Clear ();

-> ViewEngines. Engines. Add (new RazorViewEngine ());

2) You can also change the order of loading views in this way.

-> WebFormViewEngine takes precedence by default.

-> ViewEngines. Engines. Add (new WebFormViewEngine ());

(8) avoid entering the View as null)

1) Html. TextBoxFor (m => m. Name)

-> An Exception is thrown when null is passed in, but it will be caught by try/catch.

-> Public ActionResultInsert (){

Return View (new Products ());

}

(9) disable the debug mode of Web. Config.

1) <compilation debug = "False" targetFramework = "4.0"/>

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.