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

Microsoft ASP Net 3.5 Step By Step (phần 16) potx

30 301 0

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

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 30
Dung lượng 647,46 KB

Nội dung

Chapter 19 Custom Handlers 421 FIGURE 19-3 IIS has a handler mapping for Trace.axd. If you look through the default web.confi g fi le a bit more, you’ll see some other critical ASP.NET handlers. As you might expect, source code is banned explicitly from normal clients by default. Notice that fi les such as *.cs, *.confi g, and *.vb are handled by the Forbidden han- dler. If you try to look at source code via a Web browser, ASP.NET returns the page shown in Figure 19-4 by default. FIGURE 19-4 What happens when you try to view forbidden content 422 Part IV Diagnostics and Plumbing Remember that ASP.NET’s confi guration is very malleable and that you may choose to let cli- ents see your source code by one of two means. You may remove the source code extension to ASP.NET mappings within IIS. Alternatively, you may write your own source code viewer handlers and declare them in your application’s web.confi g fi le. These handlers plug into the pipeline by implementing IHttpHandler. Let’s take a look at this key interface. IHttpHandler Here it is. Shield your eyes while you look at Listing 19-2 (just kidding—it’s not a very big interface). LISTING 19-2 The IHttpHandler Interface public interface IHttpHandler { void ProcessRequest(HttpContext ctx); bool IsReusable {get;} } There’s really not much to it, is there? The interface includes a method named ProcessRequest and a property named IsReusable. If the handler instance can be used multiple times, then IsReusable should return true. If the handler generally returns static content, it’s probably reusable. If the content is dynamic, it’s probably not reusable. The heart of the handler is the ProcessRequest method that includes a single parameter: the current HttpContext. Once a request fi nally arrives at the handler (through the ProcessRequest method), ProcessRequest can literally do anything to respond to the request. The Trace.axd handler re- sponds to a GET request by listing the requests being tracked by the runtime. The forbidden handler responds by tossing a roadblock in the processing pipeline so the client can’t see the forbidden resource. A custom Web service might respond to the request by parsing the XML payload, constructing a call stack, and making a call to an internal method. Implementing IHttpHandler is simple—at least from the architectural standpoint. The ProcessRequest method takes a single parameter—the current HttpContext. However, the code inside ProcessRequest is free to do just about anything, possibly making the internal processing quite complex! The following example illustrates taking over the entire form- rendering process to display a list of choices within a combo box, allowing the end client to select from the choices, and fi nally rendering the chosen item. Writing a Custom Handler 1. Create a project named CustomHandlers. Chapter 19 Custom Handlers 423 2. Add a new class library subproject to the CustomHandlers Web site (just as you did when you created an HTTP module). Name the project CustomFormHandlerLib. The name of the class it generates for you is Class1. Rename the fi le CustomFormHandler.cs and the class CustomFormHandler. 3. The library generated by Visual Studio comes without any knowledge of the ASP.NET classes. Add a reference to the System.Web assembly. 4. To turn the CustomFormHandler class into an eligible handler, add the IHttpHandler interface to the inheritance list and implement ProcessRequest. Add a method named ManageForm that takes a parameter of type HttpContext. ManageForm should write out <html>, <body>, and <form> tags through Response.Write. Write the question “Hello there. What’s cool about .NET?” followed by a line break. Next, write a <select> tag and set the name attribute to “Feature.” Then write several .NET features surrounded by <option> tags. This will produce a drop-down list box on the client’s browser. Write out an <input> tag. The tag’s type attribute should be submit, its name attribute should be “Lookup,” and its value attribute should be “Lookup.” Next, look up the new value for the “Feature” selection tag within the HttpContext’s Request.Params collection. If the value is not null, then the end user selected something. Write the value provided by the “Feature” selection tag. Finally, write out closing tags. That is, </form>, </body>, and </ html> tags. Have the ProcessRequest method call the ManageForm method like so: using System; using System.Collections.Generic; using System.Text; using System.Web; public class CustomFormHandler : IHttpHandler { public void ProcessRequest(HttpContext ctx) { ManageForm(ctx); } public void ManageForm(HttpContext context) { context.Response.Write("<html><body><form>"); context.Response.Write( "<h2>Hello there. What's cool about .NET?</h2>"); context.Response.Write( "<select name='Feature'>"); context.Response.Write( "<option> Strong typing</option>"); context.Response.Write( "<option> Managed code</option>"); context.Response.Write( "<option> Language agnosticism</option>"); 424 Part IV Diagnostics and Plumbing context.Response.Write( "<option> Better security model</option>"); context.Response.Write( "<option> Threading and async delegates</option>"); context.Response.Write( "<option> XCOPY deployment</option>"); context.Response.Write( "<option> Reasonable HTTP handling framework</option>"); context.Response.Write("</select>"); context.Response.Write("</br>"); context.Response.Write( "<input type=submit name='Lookup' value='Lookup'></input>"); context.Response.Write("</br>"); if (context.Request.Params["Feature"] != null) { context.Response.Write("Hi, you picked: "); context.Response.Write( context.Request.Params["Feature"]); context.Response.Write( " as your favorite feature.</br>"); } context.Response.Write("</form></body></html>"); } public bool IsReusable { get { return true; } } } The code within the ProcessRequest will render a form element and a select element that renders a form that can be submitted by the browser. When the form is submitted back to the server, the parameter collection will contain a Features element. The code examines the parameter collection to see if it references a feature, and it displays the feature if it’s been selected. 5. The class library you just created deposits its output in the project directory. In order for ASP.NET to use the page, the resulting executable needs to live in the application direc- tory’s bin subdirectory. You can do this by adding the CustomHandlerLib.dll as a project reference to the Web site. Click the right mouse button on the Web site project within the Solution Explorer and add a new project reference. Navigate to the CustomFormHandlerLib project’s bin directory and choose the CustomFormHandlerLib.dll fi le. 6. Now update web.confi g so that it uses the handler when clients request the CustomFormHandler resource. If you don’t already have a web.confi g in the proj- ect, add one. Then insert an httpHandlers section that points requests for the CustomFormHandler to the new CustomFormHandler class. Chapter 19 Custom Handlers 425 <configuration > <appSettings/> <connectionStrings/> <system.web> <httpHandlers> <! There will be some other entries here > <add path="*.cstm" verb="*" type="CustomFormHandlerLib.CustomFormHandler, CustomFormHandlerLib" validate="true" /> </httpHandlers> </system.web> </configuration> Note If this site were running under IIS, you would need to tell IIS about the new fi le types to be handled by the CustomFormHandler. If you decide to run this application under IIS (instead of the Visual Studio Web server), you may confi gure IIS to run your handler by doing the following. Open IIS and drill down to the CustomHandler virtual directory. Open the Features View and lo- cate the Handler Mappings icon. Double-click on the Handler Mappings icon to bring up the Handler Mappings page. 426 Part IV Diagnostics and Plumbing Click the right mouse button in the middle of the Handler Mappings page to bring up the local menu. Select Add Managed Handler. Type in an extension you’d like to have mapped to the custom handler. Then assign a handler. IIS will look at all the handlers available to your applica- tion (including the ones local to your application). Select the handler from the drop-down list, give the handler an alias, and you’ll be able to surf to that fi le type to invoke the handler. Chapter 19 Custom Handlers 427 7. Finally, create a blank Text fi le named CustomHandler.cstm to your project. You can use the fi le with that extension to surf to the handler. 8. Surf to the customhandler.cstm resource and ASP.NET will invoke the custom handler you just created. Of course, most of this processing could be handled more easily by setting up a Web form. However, this example shows the fl exibility of the ASP.NET handler architecture. It should also give you more appreciation for the Web form and custom controls machinery within ASP.NET. Handlers and Session State In Chapter 14, we looked at session state. Session state works automatically within the con- text of System.Web.UI.Page. However, custom handlers need to turn on the ability to use ses- sion state deliberately. The .NET architecture uses an interesting idiom known as marker interfaces. Marker interfaces are empty interfaces (without any methods or properties defi ned). Their sole purpose is to signal the runtime as to various aspects of the application. For example, ASP.NET runtime of- ten uses them to turn on and off various features. When the runtime detects a marker inter- face as part of an object’s class hierarchy, the runtime can bring into play certain features. For a handler to use session state, it must have the System.Web.SessionState.IRequiresSessionState interface in its inheritance list. That way the runtime will know to load and store session state at the beginning and end of each request. Listing 19-3 shows a handler with session state enabled. LISTING 19-3 Example HTTP Handler That Accesses Session State using System; using System.Collections.Generic; using System.Text; using System.Web; using System.Web.SessionState; public class HandlerWithSessionState : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext ctx) { string strData = (string)ctx.Session["SomeSessionData"]; if (String.IsNullOrEmpty(strData)) { strData = "This goes in session state"; ctx.Session["SomeSessionData"] = strData; } ctx.Response.Write("This was in session state: " + strData); } 428 Part IV Diagnostics and Plumbing public bool IsReusable { get { return true; } } } Generic Handlers (ASHX Files) Just as ASPX fi les can be compiled on the fl y (“just in time”), so can handlers. Generic han- dlers have an extension of ASHX. They’re equivalent to custom handlers written in C# or Visual Basic in that they contain classes that fully implement IHttpHandler. They’re convenient in the same way ASPX fi les are convenient. You simply surf to them and they’re compiled automatically. The following example illustrates the CustomFormHandler implemented as a “generic handler.” Writing a generic handler 1. Add a “generic” handler to the Web site. Go to the Solution Explorer, click the right mouse button on the CustomHandler Web site node and select Add New Item. Select Generic Handler from the templates. Name the handler CustomFormHandler.ashx. 2. Visual Studio generates a handler that includes a stubbed-out ProcessRequest method and a completed IsReusable property. Write a function to emit the form-handling code (you can borrow it from the last exercise), and call the method from inside Chapter 19 Custom Handlers 429 ProcessRequest. Borrow the code from the earlier example to implement the handler. Replace the stubbed-out method and property with real implementations. <%@ WebHandler Language="C#" Class="CustomFormHandler" %> using System.Web; public class CustomFormHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { ManageForm(context); } public void ManageForm(HttpContext context) { context.Response.Write("<html><body><form>"); context.Response.Write( "<h2>Hello there. What's cool about .NET?</h2>"); context.Response.Write("<select name='Feature'>"); context.Response.Write("<option> Strong typing</option>"); context.Response.Write("<option> Managed code</option>"); context.Response.Write("<option> Language agnosticism</option>"); context.Response.Write("<option> Better security model</option>"); context.Response.Write( "<option> Threading and async delegates</option>"); context.Response.Write("<option> XCOPY deployment</option>"); context.Response.Write( "<option> Reasonable HTTP handling framework</option>"); context.Response.Write("</select>"); context.Response.Write("</br>"); context.Response.Write( "<input type=submit name='Lookup' value='Lookup'></input>"); context.Response.Write("</br>"); if (context.Request.Params["Feature"] != null) { context.Response.Write("Hi, you picked: "); context.Response.Write(context.Request.Params["Feature"]); context.Response.Write(" as your favorite feature.</br>"); } context.Response.Write("</form></body></html>"); } public bool IsReusable { get { return false; } } } 430 Part IV Diagnostics and Plumbing 3. Browse to the CustomFormHandler.ashx fi le. It should work in just the same way as the handler implemented in the CustomFormHandler class (that you wrote in the fi rst example): The advantage of using the generic handler is twofold. First, it’s usually much more conve- nient to generate a simple handler than it is to create a whole new assembly to handle the request. Second, you don’t need to confi gure either web.confi g or IIS (when it comes time to deploy). That is, ASP.NET and IIS already understand what to do when encountering resource requests with the extension of .ashx. Installing ASP.NET places those when mapping into IIS. However, ASHX fi les have the same limitations as ASPX and ASCX fi les in terms of their place in an ASP.NET project. Simple generic handlers go with the project. That is, for the handler to work, it must accompany the whole project. Alternatively, custom handlers deployed as separate assemblies may be deployed and shared among the enterprise as Global assemblies (that is, strongly named assemblies placed in the Global Assembly Cache). Summary ASP.NET includes a number of built-in classes to handle most kinds of requests. For exam ple, ASP.NET includes UI handlers (System.Web.UI.Page and System.Web.UI.Control). ASP.NET also includes a Web service handler (System.Web.Services.WebService). These classes will [...]... implementing a service by hand, you’d probably come to the following conclusion: Much of the work involved in making a Web service work is repetitive and might as well be pushed into a library That’s exactly what ASP. NET does ASP. NET handles the details of making a Web service through the System.Web.Services.WebService class Chapter 20 ASP. NET Web Services 439 A Web Service in ASP. NET ASP. NET handles Web... programming effort Remember how the ASP. NET pipeline architecture works Requests coming from clients end up at the server’s port 80 ASP. NET Web services live in a file type named with the extension asmx If the server is running ASP. NET, Internet Information Services (IIS) routes the request for files with the ASMX extension to ASP. NET, where they’re handled like any other request ASP. NET includes an attribute... Microsoft Message Queue, and NET Remoting), ASP. NET s ASMX framework is still part of the ASP. NET canon and remains a viable way to do remoting over the Internet High connectivity among computers has been a goal since personal computing began Although only a pipe dream in the earliest years, the ability to connect computers is commonplace these days With the rise of the internal company network comes the desire... Services work much the same way The fundamental remoting steps are all there However, this time around the wire format is an XML format formalized as SOAP and the Chapter 20 ASP. NET Web Services 437 connection protocol is, at least for ASP. NET, HTTP Other systems might use other connection protocols, like the Simple Mail Transfer Protocol, or SMTP ASP. NET, however, only supports HTTP Remoting over the Web... AJAX, Deployment, and Silverlight 433 Chapter 20 ASP. NET Web Services After completing this chapter, you will be able to Understand the importance of Web services Use the technologies underlying Web services Write Web services using ASP. NET Consume Web services synchronously Consume Web services asynchronously This chapter covers Web services from an ASP. NET perspective During the past decade, “Web services”... CodeBehind="~/App_Code/QuoteService.cs" Class="QuoteService" %> 4 Surf to the QuoteService.asmx file to see what a default HTTP GET renders Chapter 20 ASP. NET Web Services 441 By default, ASP. NET renders the names of the available methods when you just GET the ASMX file Notice that the HelloWorld method (provided by Visual Studio) is exposed If you want to try running the HelloWorld method, click the HelloWorld link, which renders... addition, ASP. NET automates WSDL generation, and Microsoft provides tools to automate generating client-side proxies given WSDL input from an XML Web Service The following example illustrates an XML Web Service that retrieves quotes from the quotes collection we saw in Chapters 15 and 18 This example will expose the quotes collection via a set of methods expressed as an XML Web Service Write an ASP. NET Web... component called the stub receives the network packets and turns the incoming stream into a real call on the server (deserialization) If the framework is NET Remoting, then the term for the proxy component is the transparent proxy The transparent proxy talks to the real proxy, which sends the bytes across the network Once at the server, a component called the sink unpacks the bytes and turns them into a real... Although networking a bunch of computers isn’t trivial, it’s generally a solved problem these days Most workplaces in the modern world depend on an internal network of computers to allow the people staffing the enterprise to communicate and work effectively Even though Microsoft has recently released Windows Communication Foundation (which unifies the programming model for sockets, Web services, Microsoft. .. Simple Mail Transfer Protocol, or SMTP ASP. NET, however, only supports HTTP Remoting over the Web In the previous 19 chapters, we’ve looked primarily at how ASP. NET makes it easy to handle a wide variety of Web application scenarios We’ve seen that ASP. NET handles HTTP GET and POST verbs, redirecting the request to a handler Until now, the job of the handler has been to process the incoming query string . what ASP. NET does. ASP. NET han- dles the details of making a Web service through the System.Web.Services.WebService class. Chapter 20 ASP. NET Web Services 439 A Web Service in ASP. NET ASP. NET. server is running ASP. NET, Internet Information Services (IIS) routes the request for fi les with the ASMX extension to ASP. NET, where they’re handled like any other request. ASP. NET includes an. Summary ASP. NET includes a number of built-in classes to handle most kinds of requests. For exam ple, ASP. NET includes UI handlers (System.Web.UI.Page and System.Web.UI.Control). ASP. NET also

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

TỪ KHÓA LIÊN QUAN