MVC Best Practices

Source: Internet
Author: User
Tags http post net thread

MVC Execution Process

Model the Recommendations

Model is used to define domain-specific objects. These definitions should include business logic (the behavior of the object), validation logic, data logic, and session logic (tracking the user state of the application).

make a model of your own project using separate assemblies.

Applications with large, complex models are best to create a separate model assembly to reduce coupling. You can then reference the model's assembly in an ASP. NET MVC project.

Put all the business logic in the model.

If you put all the business logic models in, you also get the following benefits:

    • Reduce duplication of business logic.
    • The view is easy to read and does not exist for business logic.
    • Test business rules are independent.

For example:

<% if (String.Compare (String) tempdata["Displaylastnamefirst"], "on") = = 0)

{%>

Welcome, <%= model.lastname%>, <%= model.firstname%>

<%}

Else

{%>

Welcome, <%= model.firstname%> <%= model.lastname%>

<%}%>

If you need this logic in many places, you have to write code like this in the view, if you put it in the model:

public string Combinedname

{

Get

{

Return (Displaylastnamefirst lastName + "+ firstname:firstname +" + lastName);

}

Private Set

{

;

}

}

This will greatly simplify the view:

<% Welcome, <%= model.combinedname%>%>

Put all the validation logic in Model the.

All input validation should be in model, including client side validation.

You can use Modelstate to add validation checks. The following example shows how to add a validation check with an explicit modelstate:

if (String.IsNullOrEmpty (userName))

{

Modelstate.addmodelerror ("username", Resources.SignUp.UserNameError);

}

The System.ComponentModel.DataAnnotations provided by the. NET Framework should be the preferred method for validation. Like what:

public class User

{

[Required (Errormessageresourcename = "namerequired", Errormessageresourcetype = typeof (Resources.user))]

Public String UserName {get; set;}

...

}

defining the data access interface

Interfaces are used to expose methods of data access providers, which can enhance the design of loosely coupled components of ASP.

Consider using the Entity Framework, or LINQ to SQL, to create call wrappers to the database.

View Recommended put HTML placed in View and the Partial views in (rather than in a Controller ).

For the default view engine, ASP. NET provides several file types: Full HTML view (. aspx), partial HTML view (. ascx), and master page (. master). Master pages enable you to specify a view of the overall layout. Master Pages can be nested several times to create a hierarchy of available layout types. If the razor view does not have a suffix name difference.

The following example shows how to invoke a detail view:

<%@ page title= "" Language= "C #" masterpagefile= "~/views/shared/site.master" inherits= "System.Web.Mvc.ViewPage"% >

...

Below is a list of items submitted by <b>

<%= Html.encode (viewdata["name"])%></b>.

<p>

...

<div id= "Items" >

<% html.renderpartial ("Itemsbyname");%>

</div>

</asp:content>

The detail view (ITEMSBYNAME.ASCX) is as follows:

<%@ Control language= "C #"%>

...

<% foreach (Seller.Controllers.Items item in (IEnumerable) Viewdata.model)

{%>

<tr>

<td>

<%= Html.encode (item.title)%>

</td>

<td>

<%= Html.encode (Item.price)%>

</td>

</tr>

<%}%>

</table>

<%}%>

A partial view is a powerful extensibility and reuse mechanism.

Accessing views using ViewData .

ASP. NET provides the following mechanisms for accessing data in a view template:

    • Viewdata.model
    • ViewData Dictionary

The recommended use of Viewmodel,viewmodel is strongly typed and can guarantee type safety.

use auto-Generate client-side validation. Insert a server-side comment in the template.

The following line shows the server-side comment:

<%--This is a server-side template review-%>

Do not use HTML annotations in view templates, as they will be rendered to a Web browser that can be viewed by potentially malicious users.

Use HtmlHelper extension methods.

Common methods:

    • Form generation (BeginForm)
    • Input field generation check (box, hidden, radio button text box)
    • Link generation (ActionLink)
    • XSS Protection (encoding)
Controller the Recommendations in the Action method displays the specified View name.

Can return directly to view ();

If so, the MVC framework first looks for /views/products/list.aspx. If it does not exist, look for /views/products/list.ascx, if not found, find /views/shared/list.aspx and then /views/ Shared/list.ascx. From the above analysis /views/shared Files of this directory can be shared across controllers, in order to avoid confusion and performance considerations, it is recommended to display the way to specify the view name.

When you submit a form, use the Post/redirect/get ( PRG ).

Based on the definition of the HTTP POST and GET verbs:

    • HTTP GET is used to not change your model (idempotent) data.
    • HTTP POST is used to change the data for your model.

Using the same URL create.aspx for Get and POST in a standard postback is a problem when the site's users get the form released to completion without waiting patiently if they click on the browser's Refresh button, which can result in duplicate data. Using the post-redirect Get mode solves this problem.

Use HandleError or in Web. config Custom error Handling Recommendations for routing

Routes are used to map the ASP. NET MVC URL directly to a controller instead of a specific file. This is to improve readability, can be better indexed by search engines.

Use custom routing when using from specific to generic routes.

Custom routes follow a specific route to the general.

Consider the following example. Consider a product catalog that has a URL, such as the following:

    • http://sellmyproducts/
    • http://sellmyproducts/Page#
    • Http://sellmyproducts/category
    • http://sellmyproducts/category/Page#

Provides the signature of the following list method (ProductsController Class):

Public ViewResult List (string category, int page)

Custom routing:

Routes. MapRoute (

Null

"",

New {controller = "products", action = "List", category = (string) null, page = 1}

);

Routes. MapRoute (

Null

"Page{page}",

New {controller = "products", action = "List", category = (string) null},

New {page = @ "\d+"}

);

Routes. MapRoute (

Null

"{category}",

New {controller = "products", action = "List", page = 1}

);

Routes. MapRoute (

Null

"{Category}/page{page}",

New {controller = "products", action = "List"},

New {page = @ "\d+"}

);

use a named routing mechanism to avoid ambiguous routing.

For example, the following named routes:

Routes. MapRoute (

"Default",

"",

New {controller = "products", action = "List", category = (string) null, page = 1}

);

Routes. MapRoute (

"Pageroute",

"Page{page}",

New {controller = "products", action = "List", category = (string) null},

New {page = @ "\d+"}

);

With these route definitions, you can create a link that resolves to "Pageroute" as follows:

<%= Html.routelink ("Next", "Pageroute",

New RouteValueDictionary (New {page = i + 1})); %>

Recommendations for scalability

There are many extensibility points within the ASP. You can replace the list of any one part, which includes the following core components:

    • Routing Engine (Mvcroutehandler)
    • Controller Factory (Icontrollerfactory)
    • View Engine (Iviewengine)

You can extend the framework by adding custom behaviors in filters, such as some standard filters included in the framework: Outputcache,handleerror, and authorize.

UseFilters Add Behavior

These filters enable the scalability of lightweight request processing pipelines.

For example, assume that you want to add the ability to log HTTP header information for each request debug issue. The following code defines a class that derives from the ActionFilterAttribute class.

public class Logheadersfilterattribute:actionfilterattribute

{

public override void OnActionExecuting (ActionExecutingContext filtercontext)

{

foreach (String header in

FilterContext.HttpContext.Request.Headers.AllKeys)

{

Debug.WriteLine ("header" + header);

Debug.WriteLine ("Value" +

FilterContext.HttpContext.Request.Headers.Get (header));

}

Base. OnActionExecuting (Filtercontext);

}

}

Add this filter to the given action method as long as the Logheadersfilter property is placed at the top of the action (or controller) you want to filter.

Testability Recommendations

One of the main advantages of the MVC pattern is the improved testability design, decoupling.

Write unit tests.

ASP. NET MVC provides a flexible architecture that allows for simple testing. Unit tests can be written using MS's unit test tools or third-party tools.

For more information about unit test ASP. NET MVC applications, see unit tests in an MVC application .

Security Recommendations

Security is an important aspect of any modern software development project. While there is no framework to provide complete security, there are many areas where you can help protect your ASP. NET MVC application.

prevent common attacks.

Web site security requires the attention of all web developers, common attack methods:

    • Cross-site scripting (XSS) attacks
    • SQL Injection
    • Cross-site request for forged files (XSRF)

To prevent cross-site scripting (XSS) attacks:

    • Disable request validation by using the validateinput property. This property will reject the wrong HTML input.
    • All user input data that is displayed is added Html.encode, whether it is the data being rendered immediately or the data to be displayed from the database.
    • The cookie sets the httponly flag. Prevent JavaScript from reading and sending cookies.

To prevent SQL injection:

    • Always use parameterized SQL queries.
    • Do not pass raw SQL to the database.
    • Use (for example, an object-relational mapping (ORM) of an entity schema that can be completely eliminated in the application code for an SQL statement.

To prevent cross-site request forgery (XSRF):

    • Using the Html.antiforgerytoken class in a form prevents the forgery of cross-site requests.
    • Add the Validateantiforgerytoken property on the action method that needs to be guaranteed
users who are authenticated and authorized to protect content. Use <%:%> (. NET 4) , to prevent XSS attack.

Before,. NET 4.0 developers will have to make sure that HTML is encoded by using code similar to the following:

<%= Html.encode (viewdata["name"])%>

This code is to prevent XSS cross-site scripting attacks.

Do not use the above syntax if you are using. NET 4. Please use the following syntax.

<%: Html.encode (viewdata["name"])%>

Localization and globalization recommendations

Globalization is the process of adapting a product's multilingual localization to a global product process that adapts to a particular language and country. To develop a Web application that supports globalization and localization, keep in mind at least one rule. Hard-coded strings are not used in the view.

Do not use ASP Special resource folders and resource files.

Add localized content for the ASP. NET project folder globalization content (App_GlobalResources) and the given view (App_LocalResources). In each of these folders you should add a resource (. resx) file, which should be named according to the name of the controller. If the controller is named Submissionpipeline, the resource file should be named Submissionpipeline.resx.

Visual Studio converts this text-mapping class to a global class that can be called using the following syntax:

Resources.<resource_filename>.<string_name>

The resources in this class of views are then accessed:

<%= Resources.SubmissionPipeline.continueButton%>

You should use the following format to name each file when you get the translated resource file: <filename>. <language>.resx.

For example, the German version of the resource file will be named: SubmissionPipeline.de.resx.

Recommendations for performance

Bottlenecks that may affect Web site performance include:

    • Database
      • Low-efficiency queries
      • Index is placed incorrectly
      • Non-normalized design
    • Bandwidth issues
      • Request size (large image,. css,. js,. html, etc.).
      • Multiple scripts referencing other projects, CSS or image file contents
      • Slow connection
    • Processing power
      • Server: Time-consuming operation
      • Client: Bad JavaScript
consider reducing bandwidth usage AJAX Partial-page updates.

Using JavaScript AJAX async to handle partial-page update requests to mitigate a problem that involves server processing stress is a way to address performance issues. ASP. NET MVC has built-in AJAX support to reduce the processing server's need to perform rendering requests and reduce the size of HTML fragments.

The following example shows how to use partial-page updates for AJAX:

1. Create Partialview test.cshtml.

@model MVC. Test.Site.Models.UserView <div id= "Items" > Username: @if (Model! = null) {@Model. Username}

</div>

2. Add in action.cshtml

@{html.renderpartial ("Test", viewdata["user"]);

3. Home/login Code

Public ActionResult Login (userview user) {viewdata["user"] = user; Return Partialview ("Action", user); }

do not overuse the session, but use the TempData storage.

Creating sites to add objects to the object of the session , so that they are always available, looks good, but the problem with putting these objects in the session object is that it can be a burden to the server because it is only used when redirect. The correct way to store these temporary variables in redirection is to use the TempData dictionary.

For example, suppose you receive a POST login form data. The initialization process may be the following action method:

[Acceptverbs (Httpverbs.post)]

Public ActionResult LogIn (Seller person)

{

...

tempdata["name"] = person. Name;

Return redirecttoaction ("Itemupload");

}

The person.name is placed in the TempData dictionary before being redirected to the Itemupload action method. The Itemupload action method is retrieved from the TempData dictionary and placed in its own viewdata so that it can be referenced in the view.

Public ActionResult Itemupload ()

{

String name = tempdata["Name"] As String;

viewdata["name"] = name;

return View ();

}

Use OutputCache .

The OutputCache property is used for infrequently updated data, primarily for the home page. For HTML and JSON data types, you can use this technique. When you use it, specify only the name of the cache configuration file; Use the Web. config file to configure the output cache section.

For example, the OutputCache property is appended to the dashboard action method in the following code.

[Acceptverbs (Httpverbs.get), OutputCache (CacheProfile = "Dashboard")]

Public ActionResult Dashboard (string userName, Storylisttab tab, by-and-by, int? page)

{

...

}

consider using asynchronous controllers for long-running requests.

The default limit for the ASP. NET thread pool is 12 concurrent worker threads per CPU. When requests are overloaded with the ability of the server to process these requests, the queue is an established request. For example, any request requires a large amount of time to wait for external resources such as databases or large file operations. These external requests prevent them from taking up the entire wait time thread. When this queue gets too large (5000 requests pending), the server starts 503 (server too busy) error response.

The number of concurrent threads in ASP. 4 is set by default, 5000. Although it is possible to increase the default limit there is a better way to mitigate long-running requests that consume a thread that modifies a long-running request to run asynchronously. ASP. NET MVC allows you to implement an asynchronous controller for this purpose. For more information about how to implement an asynchronous controller, see an asynchronous controller that uses ASP .

MVC Best Practices

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.