1. Trang chủ
  2. » Công Nghệ Thông Tin

Lập trình .net 4.0 và visual studio 2010 part 36 ppsx

6 205 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 6
Dung lượng 181,97 KB

Nội dung

CHAPTER 10  ASP.NET 238 Figure 10-5. Initiating one-click publishing ViewState ViewState is the mechanism by which ASP.NET stores the state of controls on a web form. This information is held in a hidden form value called __VIEWSTATE. Depending on the page’s content, ViewState can get pretty large, and is often unnecessary for controls that don’t change such as labels. ASP.NET 4.0 gives you the ability for controls to inherit ViewState settings from parent controls by using the new ViewStateMode property. This makes it very easy to efficiently set ViewStateMode on a large number of controls. ViewStateMode has three settings • Enabled (ViewState used) • Disabled (ViewState not used) • Inherit (ViewStateMode is inherited from parent control) The following example shows how to make lbl1 Label inherit pnlParent's ViewStateMode. <asp:Panel ID=”pnlParent” runat=server ViewStateMode=Disabled> <asp:Label ID="lbl1" Text="text" ViewStateMode=Inherit runat="server" /> </asp:Panel> CHAPTER 10  ASP.NET 239 ClientIDMode A long-term irritation in ASP.NET is the lack of control you have over the ID property of rendered controls. For example, take the following HTML that is rendered from a few simple controls that are nested inside a Master page: <span id="MainContent_label1"></span> <div id="MainContent_panel1"> <span id="MainContent_label2"></span> </div> Most of the time, ASP.NET’s automatic ID generation features work pretty well, but in some situations, say, when working with Master pages or writing client script, you need a finer level of control. ASP.NET 4.0 gives you this control with the new ClientIDMode. ClientIDMode has four settings • AutoID: Works as per previous ASP.NET releases. • Static: Allows you to specify the ID that is used. Warning: you can obviously generate duplicate client IDs, so it is up to you to ensure your ID is unique or face client-side script hell (well, probably an annoying JavaScript error, anyway). • Predictable: Used in conjunction with RowClientIdSuffix property to generate incrementing IDs for repeating controls such as DataGrid and Repeater, for example, myrow1, myrow2, myrow3. • Inherit: Controls uses the same ClientIDMode as its parent control (default). ClientIdMode can be set at control, page, and application level. • To set on an individual control: <asp:Label ID="lblTest" runat="server" Text="Test" ClientIdMode=”Inherit”></asp:Label> • At page level: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ClientIdMode="Predictable" %> • Or application wide in Web.config: <system.web> <pages clientIdMode="Inherit"></pages> </system.web> Response.RedirectPermanent() Response.Redirect() is a frequently used method that redirects the current request to another URL. At an HTTP level Response.Redirect() issues a temporary redirect (HTTP 302) message to the user’s browser. ASP.NET 4.0 now offers a new Response.RedirectPermanent() method that issues a permanently moved (HTTP 301) message (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html). Why bother? HTTP 301 is mainly used to tell search engines that they should save the new page location in their indexes rather than the old location. This saves an unnecessary trip to the server. Response.RedirectPermanent() usage is very similar to Response.Redirect(): CHAPTER 10  ASP.NET 240 Response.RedirectPermanent("/newpath/foroldcontent.aspx"); Meta-tags ASP.NET 4.0’s Page class has two new properties that allow you to set the keyword and description Meta- tags that are generated: MetaKeywords and MetaDescription properties. It is worth noting that most search engines (or certainly the big one beginning with G) probably ignore meta-tags (due to previous abuse), and that if you have already specified meta-tags on your page then MetaKeywords and MetaDescription will act as properties so make sure you append rather than overwrite when using them. URL Routing Routing was first introduced in ASP.net in .net 3.5sp1 and further enhanced in ASP.NET MVC (see Chapter 13). Routing allows you to map a URL to a physical file, which may or may not exist. To implement this functionality in previous versions of ASP.NET complex hacks or ISAPI filters were needed. Why use this feature? Well let’s say you are working for an online shop that has a new product they are advertising on TV and it is located at the following URL: www.myshop.com/productDetail.aspx?id=34534 Routing allows you to create a more readable URI mapped through to the page, such as: www.myshop.com/PopularProduct/ URL routing also allows you to create more memorable and search engine-friendly URIs, hiding the internal structure of your application. Routes are created in the Global.asax file. The code below maps the URL ~/PopularProduct to the page ~/default.aspx?id=34534: protected void Application_Start(object sender, EventArgs e) { System.Web.Routing.RouteTable.Routes.MapPageRoute( "myPopularRoute", "PopularProduct", "~/default.aspx?id=34534" ); } Routing has implications for security policies that you may have defined in Web.config, because ASP.NET will check policies for the route rather than mapped page. To remedy this, MapPageRoute supports an overloaded method that allows you to check that the user has access to the physical file (~/default.aspx?id=34534) as well. Access for defined routes is always checked. As well as creating simple one-to-one mapping URLs, it is useful to be able to pass in parameters to routes. For example most shops sell a number of different types of products so you could create URLs such as myshop.com/cats or myshop.com/dogs (note selling cats and dogs online is probably a bad idea). To create these type of routes enclose the value that will change inside curly brackets: System.Web.Routing.RouteTable.Routes.MapPageRoute( "myProductGroupRoute", "{groups}", "~/default.aspx?id=123" ); CHAPTER 10  ASP.NET 241 Routing parameters can then be retrieved with the following syntax: string searchTerm=Page.RouteData.Values["group"]; Sometimes it can also be useful to retrieve the URL that will be generated for a specific route to create hyperlinks or redirect the user; this can be done with the GetRouteUrl() method: Page.GetRouteUrl("myProductGroupRoute", new { group = "brandNew" }) HTML Encoding All web developers should be aware that it is important to HTML encode values that are output to prevent XSS attacks (particularly if you have received them from the user). ASP.NET 4.0 offers a new markup syntax that uses the colon character to tell ASP.NET to HTML encode the expression: <%: "<script>alert('I wont be run');</script>" %> When ASP.NET parses this it does the following: <%= HttpUtility.HtmlEncode(YourVariableHere) %> It is important to bear in mind that the use of this syntax may not negate all XSS attacks if you have complex nested HTML or JavaScript. HtmlString ASP.NET 4.0 includes the new HtmlString class that indicates an expression is already properly encoded and should not be re-examined. This prevents “safe” values from potentially firing dangerous request validation rules: <%: new HtmlString("<script>alert('I will now be run');</script>") %> Custom Request Validation It is now possible to override the default request validators by inheriting from the System.Web.Util.RequestValidator class and overriding the method IsValidRequestString(). You must then specify the custom validator in the httpRuntime section in Web.config: <httpRuntime requestValidationType="Apress.MyValidator, Samples" /> Custom Encoders If you feel that ASP.NET’s existing page encoders are insufficient then you can now create your own by inheriting from System.Web.Util.HttpEncoder class and specifying the new encoder in the encoderType attribute of httpRuntime, for example: <httpRuntime encoderType= =" Apress.MyEncoder, Samples" " /> CHAPTER 10  ASP.NET 242 URL and Query String Length Previously ASP.NET limited accepted URLs to a maximum of 260 characters (an NTFS constraint). ASP.NET 4.0 allows you to extend (or limit) the URL and query string maximum length. To modify these settings change the maxRequestPathLength and maxQueryStringLength properties (in the httpRuntime section) in Web.config: <httpRuntime maxQueryStringLength="260" maxRequestLength="2048"/> Valid URL Characters Previous versions of ASP.NET limit accepted URLs to a specific set of characters. The following characters were considered invalid in a URL: <, >, &. You can use the new requestPathInvalidChars property to specify invalid characters (such as the above). The below example makes a,b,c invalid in requests (which isn’t too useful but demonstrates the feature): <httpRuntime requestPathInvalidCharacters="a,b,c">  NOTE The Microsoft documentation states that ASP.NET 4.0 will reject paths with characters in ASCII range 0x00 to 0x1F (RFC 2396). Accessibility and Standards Accessibility and standards, whether you like it or not, are becoming increasingly important. Microsoft is aware of this and has introduced a number of changes. controlRenderingCompatibilityVersion The pages section in Web.config contains a new controlRenderingCompatibilityVersion property that determines how controls are rendered by default. The controlRenderingCompatibilityVersion property can be set to 3.5 or 4.0. <system.web> <pages controlRenderingCompatibilityVersion="4.0"/> </system.web> Setting controlRenderingCompatibilityVersion to 3.5 will ensure ASP.NET renders as in ASP.NET 3.5. If however you set controlRenderingCompatibilityVersion to 4.0 then Microsoft say that the following will occur: • The xhtmlConformance property will be set to Strict and controls will be rendered according to XHTML 1.0 Strict markup. • Disabled controls will not have invalid styles rendered. CHAPTER 10  ASP.NET 243 • Hidden fields that have div elements around them will now be styled in a manner that will not interfere with user-defined CSS rules. • Menu controls are now rendered using unordered list (UL) tags (fantastic). • Validation controls will not use inline styles. • Previously some controls such as Image rendered the property border="0"; this will no longer occur. RenderOuterTable Previous versions of ASP.NET used a Table tag to wrap the following controls: • ChangePassword • FormView • Login • PasswordRecovery In ASP.NET 4.0, however, all these controls support a new RenderOuterTable property that if set to false will use a div instead. CheckBoxList and RadioButtonList CheckBoxList and RadioButtonList benefit from a the new property RepeatLayout. RepeatLayout has four modes: UnorderedList, OrderedList, Flow, and Table, allowing you fine control over how they are rendered. ASP.NET Menu control The ASP.NET Menu control now renders menu items using unordered list elements. Keyboard support for the menu has also been improved so once an ASP.NET menu receives focus the user can navigate through menu items using the arrow keys. Browser Capability Files Browser capability files are used to determine how best to render content for individual browsers and are held in XML format. If you feel the need you can create your own browser provider by deriving from the HttpCapabilitiesProvider class. . Samples" " /> CHAPTER 10  ASP .NET 242 URL and Query String Length Previously ASP .NET limited accepted URLs to a maximum of 2 60 characters (an NTFS constraint). ASP .NET 4. 0 allows you to extend. similar to Response.Redirect(): CHAPTER 10  ASP .NET 2 40 Response.RedirectPermanent("/newpath/foroldcontent.aspx"); Meta-tags ASP .NET 4. 0 s Page class has two new properties that. requestPathInvalidCharacters="a,b,c">  NOTE The Microsoft documentation states that ASP .NET 4. 0 will reject paths with characters in ASCII range 0x 00 to 0x1F (RFC 2396). Accessibility and Standards Accessibility and

Ngày đăng: 01/07/2014, 21:20