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

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

30 303 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The interface includes a method named ProcessRequest and a property named IsReusable.. The heart of the handler is the ProcessRequest method that includes a single parameter: the curren

Trang 1

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

Trang 2

422 Part IV Diagnostics and Plumbing

Remember that ASP.NET’s confi guration is very malleable and that you may choose to let ents see your source code by one of two means You may remove the source code extension

cli-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 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

Trang 3

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:

Trang 4

424 Part IV Diagnostics and Plumbing

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 tory’s bin subdirectory You can do this by adding the CustomHandlerLib.dll as a project

direc-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

Trang 5

<! There will be some other entries here >

<add path="*.cstm" verb="*"

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

Trang 6

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 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

Trang 7

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 text of System.Web.UI.Page However, custom handlers need to turn on the ability to use ses-

con-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

Trang 8

428 Part IV Diagnostics and Plumbing

public bool IsReusable {

Generic Handlers (ASHX Files)

Just as ASPX fi les can be compiled on the fl y (“just in time”), so can handlers Generic 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

han-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

Trang 9

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) {

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>");

Trang 10

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 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

conve-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)

Trang 11

probably handle most of the requirements you might come across However, for those fringe cases that require custom handling, ASP.NET supports the custom handler

The endpoint for requests coming through ASP.NET is always a class implementing

IHttpHandler IHttpHandler has very little surface area You simply override the IsReusable

property and the ProcessRequest method ProcessRequest can pretty much do anything you

want it to do The example in this book included a handler that manages rendering a form and handling input

For a custom handler assembly to work, it must be mapped to a fi le path or extension in the application’s web.confi g fi le The extension must also be mapped within the IIS metabase if you intend to deploy it to IIS

ASP.NET also supports handlers that may be compiled just in time Simple handlers are easy

to create and deploy because you don’t need to modify the web.confi g fi le, nor do you need

to modify the IIS metabase

Chapter 19 Quick Reference

Create a custom handler assembly Create a new class implementing IHttpHandler.

Implement the IsReusable property.

Implement ProcessRequest.

Assign a fi le mapping to the handler in

ASP.NET

Confi gure the handler in the httpHandler segment of the

application’s web.confi g fi le.

Assign a fi le mapping to the handler in IIS Click the right mouse button on the virtual directory.

Select Properties.

Click the Confi gure button.

Click the Add button.

Add a new extension and map it to aspnet_isapi.dll.

Create a simple handler Select Web site, Add New Item.

Select Generic Handler from the templates.

Insert your own code for responding to the request.

Trang 13

433

Services, AJAX, Deployment,

and Silverlight

Trang 15

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” has emerged as a buzzword for enabling the next generation of computer connectivity 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 staffi ng the enterprise to communicate and work effectively Even though Microsoft has recently released Windows Communication Foundation (which unifi es the programming model for sockets, Web services, 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 com-monplace these days With the rise of the internal company network comes the desire to tie machines together programmatically as well That is, a program on one machine should be able to call program methods on another machine without human intervention Many enter-prises spent nearly the entire last decade of the twentieth century trying to get their comput-ers to talk to one another programmatically On the Microsoft platform, this was usually done with Distributed Component Object Model (DCOM) before NET came along

The next step in connecting computers is happening over the Internet There’s already a ubiquitous connection available (computers connected via HTTP, the HyperText Transfer Protocol) and a well-understood wire format (XML) Together, these two elements make up

XML Web Services

Remoting

The desire to call software methods “over there” from “over here” has been around ever since the advent of distributed computing networks Beginning in the days of Remote Procedure Calls all the way through the latest version of DCOM, the promise of remoting has been to

435

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

TỪ KHÓA LIÊN QUAN