Enable Custom Error Handling

You can use the web.config file to specify a common error handling page(s) for your ASP.NET Web application. The error handler in the web.config file is declared in the <customErrors> tag under the <system.web> node.

In the <customErrors> tag, you can specify the Web page to direct users to when an error occurs with the defaultRedirect attribute. If you want to redirect users on a specified error code, you can use the <error> child node to redirect users to a page depending on the status code. For example, <error statusCode="404" redirect="PageMissing.aspx"/> nested under the <customErrors> tag will redirect requests for missing pages to an error-handling page that is only for missing pages. If this is the only <error> child node, then all errors except for 4 04 will be redirected to the page defined in the <customErrors> tag.

Another useful attribute of the customErrors element is the mode. There are three modes that can be set (On, Off, and RemoteOnly). The first two settings are self explanatory. The latter of these is for turning on custom error pages for remote users only. Locally logged-on users see the standard page debugging details like Source Error, Line, and Stack Trace. This enables an administrator to troubleshoot a problem without turning off the custom errors for outside users.

ENABLE CUSTOM ERROR HANDLING

ENABLE CUSTOM ERROR HANDLING

□ Open a new document in your text editor.

_Q Add a <customErrors> tag and set the defaultRedirect attribute and the mode attribute.

Q Open the

GenericTemplate.aspx template from the Code Templates directory.

° Add an error message for the page.

□ Open a new document in your text editor.

Start a web.config file by adding <configuration> tags.

_Q Add a <customErrors> tag and set the defaultRedirect attribute and the mode attribute.

0 Save the file as web.config to the Web site.

Q Open the

GenericTemplate.aspx template from the Code Templates directory.

_Q Add a heading to the page.

° Add an error message for the page.

DEBUG YOUR ASP.NET APPLICATIONS

You can use the QueryString in the Response object to create an error page that gives more detail to the user.

Create an error on the page by changing the SQL statement to an invalid SQL statement.

— Save the page and request it from the Web server.

■ The error-handling page appears because of the error on the page.

Create an error on the page by changing the SQL statement to an invalid SQL statement.

— Save the page and request it from the Web server.

■ The error-handling page appears because of the error on the page.

You can use the Page_Error event along with enabling custom handling to handle errors on your individual ASP.NET pages. On each ASP.NET page, you can use the Page_Error event handler to trap errors on a page and run code to properly respond to the error.

Handling errors programmatically on a page starts with putting an event handler in the server-side code for the page. You can use the Page_Error event to send an error message to the user or to check for a specific error to handle that error. The error details are available through the Server.GetLastError method. This method returns the Exception object that was created for the error. The Exception object is a rich structure that contains detailed information about the trapped error. For example, the Exception.Source property contains the name of the application or the object that causes the error. The Exception.StackTrace property helps you identify the location in the code where the error occurs, and the Exception.Message property gives you error message text.

When you are done responding to the error, you need to then clear the error by using the Server.ClearError method. This is done to ensure the error is not bubbled up to any other error handling mechanisms on the site (like the custom error handling in the web.config file).

HANDLE ERRORS PROGRAMMATICALLY

HANDLE ERRORS PROGRAMMATICALLY

DatagridTemplate.aspx from the Code Templates directory.

0 Add the Page_Error event handler to the page.

Add a string variable to create an HTML message for informing the user that an error has occurred on the page.

□ Write the string to the Web browser using the Response object.

DatagridTemplate.aspx from the Code Templates directory.

0 Add the Page_Error event handler to the page.

Add a string variable to create an HTML message for informing the user that an error has occurred on the page.

□ Write the string to the Web browser using the Response object.

Clear the error using the Server.ClearError method.

DEBUG YOUR ASP.NET APPLICATIONS

Because you are on the same page in which the error occurred, you can print out a number of details about the error.

Example:

<SCRIPT LANGUAGE="C#" RUNAT="Server">

void Page_Error(Object sender, EventArgs e) {

String stringMessage = "<HTML><FONT FACE =\"Verdana\">"

+ "<H3>Handle Errors Programmatically</H3>"

+ "There was an error processing this page."

+ "<P/>Here is the error information:<P/><PRE>" + Server.GetLastError().ToString()

+ "</PRE></FONT></HTML>";

Response.Write(stringMessage);

Server.ClearError();

L0 Create an error on the page by changing the SQL statement to an invalid SQL statement.

Q Save the page and request it from the Web server.

■ You remain on the same page and an error message appears.

USE A PAGE-LEVEL TRACE

You can use page tracing on your individual ASP.NET pages to get information about the page request when attempting to debug your site. Tracing can be set on the page level with the @Page directive. To trace an ASP.NET Web page, you need to add <%@ Page-Trace="true" %> to the top of the page. When the page is requested, the trace information appears.

With traces you can inspect the common collection of the HttpRequest and execution flow (timing and call stack). The Trace Information section displays the different functions and their associated execution times. The Control Tree section shows detailed information about the use of controls and control hierarchy for the page. The Cookies Collection section displays all the cookies sent in the request. The Headers Collection section shows the name value pairs sent in the header section of the request. The Server Variables section displays information about the server, including security and configuration information.

The trace information for a page appears at the bottom of the page. You can add your own trace information to page level traces. The trace information is available to you through the

TraceContext object. This object can be accessed by using the Trace property of a Page or through the HttpContext.

USE A PAGE-LEVEL TRACE

USE A PAGE-LEVEL TRACE

http://localhostyPageLeveITiace.aspx - Microsoft Internet Explorei

File Edit View Favorites Tools Help

DatagridTemplate.aspx from the Code Templates directory.

0 Turn on tracing for the page by setting the Trace="true" attribute for the @Page directive.

http://localhostyPageLeveITiace.aspx - Microsoft Internet Explorei

File Edit View Favorites Tools Help

JsJjiJ

] http: //localhost/PageLevelT race, aspx

Welcome to mylifetimegoals.com

Here are the are some books that will help you reach your career goals.

Welcome to mylifetimegoals.com

Here are the are some books that will help you reach your career goals.

title

notes

price

The Busy Executive's Database Guide

An overview of available database systems with emphasis on common business applications. Illustrated.

19.99

Cooking with Computers: Surreptitious Balance Sheets

Helpful hints on how to use your electronic resources to the best advantage.

11,95

You Can Combat Computer Stress!

The latest medical and psychological techniques for living with the electronic office, Easy-to-understand explanations.

2,99

Straight Talk About Computers

Annotated analysis of what computers can do for you: a no-hype guide for the critical user.

DatagridTemplate.aspx from the Code Templates directory.

0 Turn on tracing for the page by setting the Trace="true" attribute for the @Page directive.

Q Save the page and request it from the Web server.

The page contents appear.

□ Scroll down the page until you get to the Request Details.

DEBUG YOUR ASP.NET APPLICATIONS

ly

You can write to the Trace Information from within your ASP.NET Web page to track significant sections of code. This is useful not only for outputting values at certain times, but also for seeing how long it takes for something to execute. For the full version of the code refer to PageLevelTrace_ai.aspx.

fit

TYPE THIS:

protected void Page_Load(Object sender, EventArgs e) { SqlConnection sqlconnectionPubs = new SqlConnection

("server=(local)\\NetSDK;uid=QSUser;pwd=QSPassword;database=pubs"); SqlDataAdapter sqldataadapterTitles = new SqlDataAdapter ("select title, notes, price from titles " + "where type='business'", sqlconnectionPubs); DataSet datasetTitles = new DataSet(); sqldataadapterTitles.Fill(datasetTitles, "titles");

datagridTitles.DataSource=datasetTitles.Tables["titles"].DefaultView; Trace.Write("DataBind","About to bind the datagrid.");

datagridTitles.DataBind();

Trace.Write("DataBind","Done binding the datagrid.");

}

V

1

RESULTS:

1

Trace information that includes details on the start and completion of the datagrid binding.

J

htlp://localhost/PageLevelTiace_aspx - Microsoft Internet Exploier

File Edit View Favorites Tools Help

] http: /VIocalhost/PageLevelT race, aspx

Request Details

Session Id: Time of Request: Request Encoding:

nofmhb45jvthau45wp4a0iif 8/2/2001 11:35:40 AM Western European (ISO)

Request Type:

Status Code:

Response Encoding:

Western European (ISO)

"3

Trace Information

Category

Message

From First(s)

From Last(s)

aspx.page

Begin Init

aspx.page

End Init

0,000135

0,000135

aspx.page

Begin PreRender

1,269407

1,269271

aspx.page

End PreRender

1,269551

0,000144

aspx.page

Begin SaveViewState

1,381692

0,112141

aspx.page

End SaveViewState

1,405368

0,023676

aspx.page

Begin Render

1,405500

0,000132

aspx.page

End Render

1,439191

Control Tree a do,

The Request Details appear.

The Trace Information appears.

■ The Control Tree appears.

0 Scroll down the page until you get to the Cookies Collection.

-■ The Cookies Collection appears.

-■ The Headers Collection appears.

U The Server Variables appear.

USE AN APPLICATION-LEVEL TRACE

You can use application-level tracing to view details on a series of requests made to your ASP.NET Web application. Application-level tracing is part of your Web configuration file

To enable application-level traces, you need to add the trace element under the <system.web> tag. For application traces to work properly, you need the web.config file at the root directory of your ASP.NET application. Therefore, the web.config file must be either in its own Web site or virtual directory that is configured as an application (see page 10 for further information on setting up Web sites and virtual directories).

After your site is configured for application tracing, all subsequent requests will be collected in a trace log. When you are ready to view these traces, you request a special file called trace.axd from the root directory. The trace.axd is not a physical file on your hard drive. When the trace.axd is requested in a URL, it will have the Web server generate a page that displays a master list of all the captured traces. From this master list, you can click the "View Details" hyperlink on the last column to see the details of the request. The details are very similar to what you would find on a page-level trace.

USE AN APPLICATION-LEVEL TRACE

USE AN APPLICATION-LEVEL TRACE

□ Open a new document in your text editor.

-Q Add a <trace> tag and set the enabled attribute.

~0 Request the Trace.axd page in the root directory for the application.

Q Click the View Details link to see the details for a specific request.

□ Open a new document in your text editor.

Start a web.config file by adding <configuration> tags.

-Q Add a <trace> tag and set the enabled attribute.

0 Save the file as web.config to the Web site.

~0 Request the Trace.axd page in the root directory for the application.

-■ Recent requests are displayed. You may need to open another instance of your Web browser and request some of the other files in the directory to see requests in the trace.

Q Click the View Details link to see the details for a specific request.

DEBUG YOUR ASP.NET APPLICATIONS

You can fine tune the storage of your trace information with the attributes on the trace element. The requestLimit is the number of requests to trace. The default for this is 10 requests. You can specify whether to have individual pages output trace information by setting the pageOutput = "true". You can also sort the trace information by category, instead of time, by specifying traceMode="SortByCategory".

Example:

<configuration>

<system.web>

<customErrors defaultRedirect="error

aspx" mode="on" />

<trace enabled="true" requestLimit

="50" pageOutput="true"

traceMode="SortByCategory" />

</system.web>

</configuration>

http://localhost/Tiace.and?id=0 - Microsoft Internet Explorer

File Edil View Favorites Tools Help g] Done

-■ Details appear for the request selected, including the Trace Information.

0 Scroll down the page until you get to the Cookies Collection.

http://localhost/Tiace.and?id=0 - Microsoft Internet Explorer

File Edil View Favorites Tools Help http:

^localhostA race. axd?id=0

Cookies Collection

IName

ASP.NET_SessionId

Value nofmhb45jvthau45wp4a0nf n

Cookies Collection

Value nofmhb45jvthau45wp4a0nf

Headers Collection

Name

Value

Connection

Keep-Alive

Accept

image/gifj image/x-xbitmap, image/jpegj image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*

Accept-Encoding

gzip, deflate

Accept-Language

en-us

Cookie

ASP.NET_SessionId=nofmhb45jvthau45wp4a0iif

Host

localhost

Re fere r

http://localhost/

User-Agent

Mozilla/4,0 (compatible; MSIE 6.0b; Windows NT S,0; COM+ 1.Ü.261S)

Server Variables

Server Variables g] Done

-■ Details appear for the request selected, including the Trace Information.

0 Scroll down the page until you get to the Cookies Collection.

■ The Cookies Collection appears.

-■ The Headers Collection appears.

I liâx Local intranet

U The Server Variables appear.

USING WINDOWS AUTHENTICATION

You can use Windows Authentication for securing access to your ASP.NET application. To secure your applications, you can use Windows Authentication in conjunction with the IIS Integrated Windows Authentication feature so that ASP.NET will attempt to use the browser's security context to authenticate the user.

Alternatively, you can use Windows Authentication with Basic Authentication if you want to support a wider range of browser types. IIS's Integrated Windows Authentication works only with Microsoft Internet Explorer. If you are using Basic Authentication, you need to be aware that passwords are sent over the wire in clear text. Consequently, you should only use Basic Authentication over a Secured Sockets Layer (SSL) via HTTPS.

To set up Windows Authentication, you need to add a section to the web.config file. In the <system.web> section of the web.config file, you can add an <authentication> section and set the mode attribute to Windows. Additional, the directory where you have code that uses Windows Authentication needs to be run as an application. You can accomplish this by setting directory properties in Internet Services Manager. Also, to force Windows Authentication, be sure to turn off anonymous access to the application.

USING WINDOWS AUTHENTICATION

USING WINDOWS AUTHENTICATION

Name

Q Open a new document in your text editor.

L-0 Add the <configuration> start and end tags.

< Add the <system.web> start and end tags.

^Q Add an <authentication> tag and set an attribute named mode equal to Windows.

L-0 Open the Internet Services Manager and expand the tree until you get to the directory where you want to save your code for this task.

jsjx]

Name

I Path

L<§ Scripts ^IISHelp ^IISAdmin NSSamples MSADC

Piinteis

CiystalRepoitWeb... QuickS tail ClassViewer _aspn „private _vti_cnf _vti_log _vti_pvt _vti_sciipt _vti_tnt help.gif iisstarUsp c:\inetpub\scripts c: \winnt\help\iishelp C: \WI N N T ^Siistem32\inetsr v\iisadmin c: \inetpub\iissamples c:\program files\common filesSsystemSmsadc C:\Program FilesVCommon FilesVMicrosoft Shared\Web Se... C: \WI N N T Web^printers c:\Program FilesVMicrosoft Visual Studio.NETVCiystal Repo... C: SProgram FilesVM icrosoft. N eKFiamewoikS D K^S amplest... C: \Program Files\M icrosoft. N et\Frame workS D K\S amples Y..

Q Open a new document in your text editor.

L-0 Add the <configuration> start and end tags.

< Add the <system.web> start and end tags.

^Q Add an <authentication> tag and set an attribute named mode equal to Windows.

Q Save the file as web.config.

L-0 Open the Internet Services Manager and expand the tree until you get to the directory where you want to save your code for this task.

Q Right-click the directory and choose Properties.

SECURITY AND ASP.NET

You can check to see if users are authenticated and dynamically update controls to display a message to the users based on whether they are authenticated or not. To get the full code sample, see the WindowsAuthenication_ai.aspx file companion CD-ROM.

You can check to see if users are authenticated and dynamically update controls to display a message to the users based on whether they are authenticated or not. To get the full code sample, see the WindowsAuthenication_ai.aspx file companion CD-ROM.

■ The Properties dialog box opens.

—O Click the Directory Security tab.

I Click the Edit button to open the Authentication Methods dialog box.

± Click OK to close the Properties dialog box.

■ The Properties dialog box opens.

—O Click the Directory Security tab.

I Click the Edit button to open the Authentication Methods dialog box.

Click the Anonymous access check box to turn off access for the application.

Click OK to accept the changes and close the Authentication Methods dialog box.

± Click OK to close the Properties dialog box.

CONTINUED

USING WINDOWS AUTHENTICATION

You can use Windows Authentication to manage authentication with user accounts that are stored in your Windows 2000 domain. Using Windows Authentication assumes that the user accessing your site has a user account on the Windows 2000 Server domain that is running the Web server.

For users to request a resource on a Web site, they must be mapped to a valid user account on that Web server. Most publicly available sites on the World Wide Web do not want to create a Windows 2000 account for every user of the site. This would be an administrative nightmare, so sites are typically configured to run all users under the same account.

Administrators do this by enabling anonymous access. Anonymous access will map all users that access a Web server to one account that you specify in the Internet Services Manager.

Administrators must also manage another security concept — impersonation. After a user has access to the Web server, he or she has to make requests on behalf of the user that requested a URL. You have the ability to impersonate another user if your Web application needs to run under one account for all users. You can configure impersonation in the web.config file with the identity element under the <system.web> tag.

USING WINDOWS AUTHENTICATION (CONTINUED)

USING WINDOWS AUTHENTICATION (CONTINUED)

E Open the

GenericTemplate.aspx template from the Code Templates directory.

£ Add a message to the user about their authentication and use a label control to hold the value.

Add the Page_Load event handler to the page by using the <SCRIPT> tags.

E Open the

GenericTemplate.aspx template from the Code Templates directory.

£ Add a message to the user about their authentication and use a label control to hold the value.

£ Add a message to the user '—about how they are authenticated as and use a label control to hold the value.

Add the Page_Load event handler to the page by using the <SCRIPT> tags.

SECURITY AND ASP.NET

When securing Web applications, you deal with authentication, authorization, and impersonation.

Authentication is the process of identifying if you are a configured user of the system. Authentication occurs after the user provides a name/password pair that they enter when logging on to the site. This name/password pair is also called the user credentials.

After you have authenticated a user, you need a way to determine the appropriate access rights of the user to read, modify, delete, and so on, resources on your Web site. This is known as user authorization.

Sometimes the user is mapped over to an account that is shared by multiple users. This is called impersonation and is used for setting up anonymous access to a Web application in IIS 5.0.

Be cautious when configuring impersonation, because configuration requires you to insert the password in the text of the web.config file. (Passwords in a text file are not very secure.)

Set the values for the labels including the username and the authentication type.

E Save the file and request it from the Web server.

■ A message appears showing the username and authentication type.

Set the values for the labels including the username and the authentication type.

E Save the file and request it from the Web server.

■ A message appears showing the username and authentication type.

USING FORMS AUTHENTICATION

You can build a custom login page with Forms Authentication for securing your ASP.NET applications. ASP.NET Forms Authentication is not the most secure option, but if you cannot use Integrated Windows Authentication or do not want to use the Windows Logon dialog box, it is the best alternative.

Forms Authentication uses cookies to indicate whether the user is authenticated. When users access a resource without the cookie present, they are redirected to a predetermined custom login page that collects authentication information. When users submit their user credentials, the page authenticates the user. If authenticated, the Web server sends back an authentication cookie in the header. This cookie is passed in the request header in future requests to allow users to bypass the login page on subsequent page request. The user will have this cookie until the specified timeout occurs.

To set up Forms Authentication, you need to add an <authentication> section to your web.config file. After you have set up the authentication section, you can use an <authorization> section to give specific rights to users (note that ? represents all anonymous identities, and * represents all identities). You also need to set up the directory to run as an application using the Internet Services Manager.

USING FORMS AUTHENTICATION

USING FORMS AUTHENTICATION

D Open a new document in your text editor.

L-B Add the <configuration> start and end tags.

< Add the <system.web> start and end tags.

L-Q Add an <authentication> tag and set the mode attribute equal to Forms.

^0 Add a <forms> tag and set the name equal attribute to a unique name, a loginURL attribute equal to the name of your login page, a protection attribute equal to the value of all, and a timeout attribute equal to 60.

0 Add a set of <authorization> start and end tags.

D Open a new document in your text editor.

L-B Add the <configuration> start and end tags.

< Add the <system.web> start and end tags.

L-Q Add an <authentication> tag and set the mode attribute equal to Forms.

^0 Add a <forms> tag and set the name equal attribute to a unique name, a loginURL attribute equal to the name of your login page, a protection attribute equal to the value of all, and a timeout attribute equal to 60.

0 Add a set of <authorization> start and end tags.

—Q Add a <deny/> tag with the users attribute set to ?.

0 Save the file as web.config.

SECURITY AND ASP.NET

RESULT:

If you request another page in the site (test with FormsAuthenicationDefault.aspx page), you will get this custom login page. After you supply credentials (where password = "goals"), you will be sent to the original page that you requested.

TYPE THIS:

<SCRIPT LANGUAGE="C#" RUNAT="Server"> void SubmitBtn_Click(object Source, EventArgs e) { if (inputPassword.Text == "goals") {

FormsAuthentication.RedirectFromLoginPage(inputName.Text, false);

labelMessage.Text="That password is not correct.";

GenericTemplate.aspx template from the Code Templates directory.

—— Create the Page_Load event handler to set the user name for the label control.

FormsAuthentication

Default.aspx.

GenericTemplate.aspx template from the Code Templates directory.

I Add a heading for the page that contains a label control for displaying the user name.

—— Create the Page_Load event handler to set the user name for the label control.

FormsAuthentication

Default.aspx.

CONTINUED

USING FORMS AUTHENTICATION

If you use Forms Authentication, you can use user data stores other than Windows 2000 domain accounts for determining valid users. To set up Forms Authentication, you need to create a login page that authenticates the user. ASP.NET uses the page specified in the loginUrl attribute of the forms element found under the <authentication> section. At a minimum, this page requires a place for the user to enter a user name and password. You could include some other special credentials that are part of identifying a user, such as the company name. After you retreive all necessary credentials, you can check them against the store of your user data. This could be a SQL database, Active Directory, or some other user data store. After users log into this page with your credentials, they are redirected to the original page. This redirection is not automatic. It is programmed into the function that handles the submit of the login page with the use of the FormsAuthentication. RedirectFromLoginPage method.

The form used to collect the user credentials contains sensitive information and should not be sent over an unencrypted line. To protect you user credentials, you want to put this form in a protected directory where Secured Sockets Layer (SSL) is configured. This will send this page over HTTPS instead of HTTP.

USING FORMS AUTHENTICATION (CONTINUED)

USING FORMS AUTHENTICATION (CONTINUED)

E Open the

GenericTemplate.aspx template from the Code Templates directory.

£ Add a form control to the page.

>-E Add a text box for the user name and password, along with a submit button and a label for displaying messages.

-E Add an alias to the System.Web.Security namespace using @Import.

E Check the password field for the correct input and use the

RedirectFromLoginPage to forward on the user.

E Open the

GenericTemplate.aspx template from the Code Templates directory.

L-E Add a heading for the page and a message about login.

£ Add a form control to the page.

>-E Add a text box for the user name and password, along with a submit button and a label for displaying messages.

-E Add an alias to the System.Web.Security namespace using @Import.

—§ Create the SubmitBtn_Click event handler.

E Check the password field for the correct input and use the

RedirectFromLoginPage to forward on the user.

L-E If the user did not enter correct input, set an appropriate message for the

user.

SECURITY AND ASP.NET

When collecting user credentials, you can validate server controls to ensure that the user enters all required fields before the validation check is performed.

TYPE THIS:

<FONT FACE ="Verdana"><H3>Welcome to mylifetimegoals.com</H3>

Please login to the secured area. You can use "goals" as a guest password.

<FORM RUNAT="Server">

Enter Name: <ASP:TEXTBOX ID=ninputName"

TEXTMODE="SingleLine" TEXT="" WIETH="200px" RUNAT="Server"/> <ASP:REQUIREDFIELDVALIDATOR CONTROLTOVALIDATE="inputName" DISPLAY="Static" ERRORMESSAGE="Please enter your name." RUNAT="Server"/> <BR/>

Enter Password: <ASP:TEXTBOX ID="inputPassword" TEXTMODE="Password" TEXT="" WIDTH="200px" RUNAT="Server"/> <ASP:REQUIREDFIELDVALIDATOR CONTROLTOVALIDATE="inputPassword"

DISPLAY="Static" ERRORMESSAGE="Please enter a password." RUNAT="Server"/> <P/>

<ASP:BUTTON OnClick=nSubmitBtn_Click" TEXT="Sutm±t" RUNAT="Server"/>

<ASP:LABEL ID="labelMessage" style="color:red" RUNAT="Server"/>

RESULT:

If you request another page in the site (test with FormsAuthenication Default.aspx page), you will get this custom login page. After you supply credentials (where password = "goals"), you will be sent to the original page that you requested.

Q Save the file as FormsAuthenication Login.aspx and request the FormsAuthenication Default.aspx file from the Web server.

FormsAuthenication Login.aspx page appears.

° Type a name and goal for the password.

FormsAuthenication Default.aspx page appears, and the message is personalized by using your user name.

Was this article helpful?

0 0

Post a comment