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

ASP.NET 4 Unleased - p 118 pot

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

Đ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 10
Dung lượng 676,88 KB

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

Nội dung

CHAPTER 25 Using the ASP.NET URL Routing Engine In the following route configuration, we have a category browser page that we can reach with the “/category/{name}” route pattern.. Supply

Trang 1

CHAPTER 25 Using the ASP.NET URL Routing Engine

In the following route configuration, we have a category browser page that we can reach

with the “/category/{name}” route pattern If the user doesn’t supply a category name, we

supply a default:

// URL pattern with defaults

routes.MapPageRoute(“category-browse”,

“category/{categoryname}”,

“~/Category.aspx”,

true,

new RouteValueDictionary()

{

{“categoryname”, “explosives”}

});

In this case, the default supplied is the “explosives” category The target page doesn’t need

to know that it was invoked with a default value; it can simply grab the category name

from the RouteData dictionary

Supplying defaults is useful both for creating default landing options for hitting pages

without parameters, but also so that the target page doesn’t need to be cluttered up with

conditional statements checking to see whether particular values have been supplied in

route data

Using Constrained Routes

For a lot of situations, the type of route patterns that we have discussed thus far are

suffi-cient If you want static routes, or routes with simple parameters (with or without

defaults), you are all set

However, if you want to further constrain your route patterns so that only after certain

conditions are met should your route be invoked, you’re also in luck One of the overloads

of the MapPageRoute method that we haven’t yet discussed actually takes a dictionary of

constraints to route parameters These constraints come in the form of regular expressions

(We warned you earlier that we’d have to talk about them eventually.)

At their simplest level you can use these regular expressions to limit the size of parameters

so that when passing a state code on the URL, the code must be only two characters and

must not contain numbers Anyone familiar with regular expressions also knows that you

can create incredibly powerful expressions that do far more than just simple validation

Regular expressions are outside the scope of this book, so we’re going to use some simple

expressions to illustrate their use in constraining route patterns

The code below adds a new route to our blog system This pattern restricts the year to no

more than 4 digits, but the year can also be missing The day and month parameters

receive similar treatment, both enabling between 0 (missing) and 2 digits each Because

we’re forcing them to be digits through the regular expression constraints means that the

route will not be used if any non-numeric characters are passed on the URL

Trang 2

Advanced URL Routing

NOTE

Remember that just because we use regular expressions to enforce a rule on our

para-meters limiting the data to only digits, that doesn’t mean the parapara-meters will be

con-verted to integers for us On the target page, we still need to perform the appropriate

data conversion from strings

// URL pattern with constraints

routes.MapPageRoute(

routeName: “constrained-blog”,

routeUrl: “cblog/{year}/{month}/{day}”,

physicalFile: “~/Blog.aspx”,

checkPhysicalUrlAccess: true,

defaults: new RouteValueDictionary() {

{ “year”, DateTime.Now.Year.ToString() },

{ “month”, DateTime.Now.Month.ToString() },

{ “day”, DateTime.Now.Day.ToString() }

},

constraints: new RouteValueDictionary() {

{ “year”, @”\d{0,4}” },

{ “month”, @”\d{0,2}” },

{ “day”, @”\d{0,2}” }

}

);

In a small amount of code, we accomplish quite a bit The first thing you see is that we

supplied some default values for this route The default values are set to the year, month,

and day when the application started Keep in mind that these won’t change, so if your

application has a long uptime, these values could lose their usefulness However, they do

the trick for this particular demo

The next thing to look at is the RouteValueDictionary containing the constraints The

year parameter is mapped to a regular expression indicating it can be a digit between 0

and 4 digits The month and day parameters are constrained to digits between 0 and 2

digits In a real-world scenario you might choose better regular expressions but, as we said,

regular expressions are outside the scope of this book, and plenty of great resources are on

the Internet including a great site at http://www.regular-expressions.info

Another thing you might have noticed is that all the method arguments have names This

is a great new feature of NET 4 that makes method overloads with large numbers of

argu-ments vastly more readable Without the named arguargu-ments, you would have difficulty

deciphering what the two dictionaries were and why they contained those values If you

find yourself dropping to a multiline method invocation because of a large number of

argu-ments, also consider using named arguments to make your code that much easier to read

Trang 3

CHAPTER 25 Using the ASP.NET URL Routing Engine

Security Concerns with Routes

At this point you might be wondering how the URL routing system integrates with

ASP.NET’s declarative, location-based security system It actually integrates quite well You

might have noticed that in several of the samples in this chapter we have been passing a

parameter called checkPhysicalUrlAccess when creating route patterns

This parameter, when true, tells ASP.NET that it should enforce location-based security

after determining which ASPx page to call in response to a given pattern This means that

if you have a pattern that looks like this:

http://my.app.com/blog/2010/01/02

and maps to the following location:

/contentsystem/blogapp/posts.aspx

you can define a <location> element in your web.config to secure the physical location

the same way you would normally secure that location, and permissions will be checked

before the user gets to that page

If the web.config-based security system doesn’t work for you, you can always enforce

indi-vidual permission checks at the page level either by hooking into the page life cycle or by

placing code in the code-behind—all tactics that you would use with a traditional ASP.NET

application

Summary

This chapter has provided you with an introduction and a thorough overview of the

ASP.NET URL routing engine and how to use it It provides flexibility and power for

devel-opers, user-friendly URLs, and even a URL syntax that can provide added value and

addi-tional information to search engine crawlers All this adds up to a powerful system that

can make your website more powerful and easier to use by humans and computers alike

If you’re like us, at this point after having discovered the new routing engine, you’re

prob-ably wondering where this tool has been all your life Our exercise for you now is to go

forth and create route maps and websites with friendly, easy-to-use URL syntax

Trang 4

Using the Login

Controls

IN THIS CHAPTER

Overview of the Login Controls Using the Login Control Using the CreateUserWizard Control

Using the LoginStatus Control Using the LoginName Control Using the ChangePassword Control

Using the PasswordRecovery Control

Using the LoginView Control Summary

You can use the ASP.NET Login controls to easily build a

user registration system for your website You can use the

Login controls to display user registration forms, login forms,

change password forms, and password reminder forms

By default, the Login controls use ASP.NET Membership to

authenticate users, create new users, and change user

prop-erties When you use the Login controls, you are not

required to write any code when performing these tasks

NOTE

ASP.NET Membership is discussed in detail in the

following chapter

In the first part of this chapter, you are provided with an

overview of the Login controls You learn how to

password-protect a section of your website and enable users to register

and log in to your website

In the remainder of this chapter, you learn how to use each

of the following Login controls in detail:

Login—Enables you to display a user login form

CreateUserWizard—Enables you to display a user

registration form

LoginStatus—Enables you to display either a log in or

log out link, depending on a user’s authentication

status

LoginName—Enables you to display the current user’s

registered username

Trang 5

CHAPTER 26 Using the Login Controls

ChangePassword—Enables you to display a form that allows users to change their

passwords

PasswordRecovery—Enables you to display a form that allows users to receive an

email containing their password

LoginView—Enables you to display different content to different users depending on

the their authentication status or role

Overview of the Login Controls

You won’t have any fun using the Login controls unless you have confidential

informa-tion to protect Therefore, let’s start by creating a page that needs password protecinforma-tion

Create a new folder in your application named SecretFiles and add the page in Listing 26.1

to the SecretFiles folder

LISTING 26.1 SecretFiles\Secret.aspx

<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” >

<head id=”Head1” runat=”server”>

<title>Secret</title>

</head>

<body>

<form id=”form1” runat=”server”>

<div>

<h1>This Page is Secret!</h1>

</div>

</form>

</body>

</html>

There is nothing special about the page in Listing 26.1 It just displays the message This

Page is Secret!

To password-protect the Secret.aspx page, you need to make two configuration changes

to your application: You need to configure both authentication and authorization

First, you need to enable the proper type of authentication for your application By

default, Windows authentication is enabled To use the Login controls, you need to enable

Forms authentication by adding the web configuration file in Listing 26.2 to the root of

Trang 6

Overview of the Login Controls

LISTING 26.2 Web.Config

<?xml version=”1.0” encoding=”utf-8”?>

<configuration>

<system.web>

<authentication mode=”Forms” />

</system.web>

</configuration>

The web configuration file in Listing 26.2 contains an authentication element that

includes a mode attribute The mode attribute has the value Forms

NOTE

Authentication and authorization is discussed in more detail in Chapter 27, “Using

ASP.NET Membership.”

By default, all users have access to all pages in an application If you want to restrict access

to the pages in a folder, you need to configure authorization for the folder

If you add the web configuration file in Listing 26.3 to the SecretFiles folder, anonymous

users are prevented from accessing any pages in the folder

LISTING 26.3 SecretFiles\Web.Config

<?xml version=”1.0”?>

<configuration>

<system.web>

<authorization>

<deny users=”?”/>

</authorization>

</system.web>

</configuration>

The web configuration file in Listing 26.3 contains an authorization element This

element contains a list of authorization rules for the folder The single authorization rule

in Listing 26.3 prevents anonymous users from accessing pages in the folder (The ?

repre-sents anonymous users.)

VISUAL WEB DEVELOPER NOTE

If you prefer, you can use the Web Site Administration Tool to configure authentication

and authorization This tool provides you with a form interface for performing these

con-figuration changes When using Visual Web Developer, you can open the Web Site

Administration Tool by selecting Website, ASP.NET Configuration

Trang 7

ptg CHAPTER 26 Using the Login Controls

FIGURE 26.1 Displaying a Login form

If you attempt to request the Secret.aspx page after adding the web configuration file in

Listing 26.3, you are redirected to a page named Login.aspx automatically Therefore, the

next page that we need to create is the Login.aspx page (By default, this page must be

located in the root of your application.)

The Login.aspx page in Listing 26.4 contains a Login control The Login control

automat-ically generates a login form (see Figure 26.1)

LISTING 26.4 Login.aspx

<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” >

<head id=”Head1” runat=”server”>

<title>Login</title>

</head>

<body>

<form id=”form1” runat=”server”>

<div>

Trang 8

ptg Overview of the Login Controls

<asp:Login

id=”Login1”

CreateUserText=”Register”

CreateUserUrl=”~/Register.aspx”

Runat=”server” />

</div>

</form>

</body>

</html>

The Login control includes a CreateUserText and CreateUserUrl property Adding these

properties to the Login control causes the control to display a link to a page that enables a

new user to register for your application The Login control in Listing 26.4 links to a page

named Register.aspx This page is contained in Listing 26.5

LISTING 26.5 Register.aspx

<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” >

<head id=”Head1” runat=”server”>

<title>Register</title>

</head>

<body>

<form id=”form1” runat=”server”>

<div>

<asp:CreateUserWizard

id=”CreateUserWizard1”

ContinueDestinationPageUrl=”~/SecretFiles/Secret.aspx”

Runat=”server” />

</div>

</form>

</body>

</html>

The Register.aspx page contains a CreateUserWizard control This control automatically

generates a user registration form (see Figure 26.2) After you submit the form, a new user

is created, and you are redirected back to the Secret.aspx page

Trang 9

FIGURE 26.2 Displaying a registration form

WARNING

The default ASP.NET Membership provider requires you to create a password that

con-tains at least seven characters, and at least one of the characters must be

nonal-phanumeric (not a letter and not a number) So, secret_ is a valid password, but

secret9 is not In the next chapter, you learn how to change these default password

complexity requirements

That’s all there is to it We have created a complete user registration system without

writing a single line of code All the messy details of storing usernames and passwords are

taken care of by ASP.NET Framework in the background

Using the Login Control

The Login control renders a standard user login form By default, the Login control uses

ASP.NET Membership to authenticate users However, as you see in a moment, you can

customize how the Login control authenticates users

The Login control supports a large number of properties that enable you to customize the

appearance and behavior of the control (too many properties to list here) The page in

Listing 26.6 illustrates how you can modify several of the Login control’s properties to

CHAPTER 26 Using the Login Controls

Trang 10

ptg Using the Login Control

LISTING 26.6 ShowLogin.aspx

<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” >

<head id=”Head1” runat=”server”>

<style type=”text/css”>

.login

{

width:250px;

font:14px Verdana,Sans-Serif;

background-color:lightblue;

border:solid 3px black;

padding:4px;

}

.login_title

{

background-color:darkblue;

color:white;

font-weight:bold;

}

.login_instructions

FIGURE 26.3 Customizing the Login form

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

TỪ KHÓA LIÊN QUAN