Add OpenID Login Support In Your ASP.NET Application

29. August 2010 14:50

API ASP.NET Visual Studio 

Few days back I was looking at Scott Hanselman and friend's Open Source Nerddinner project, learning and grabbing some new things from there. Apart from looking some internals I looked at the OpenID implementation. This was all a week ago and now it's time for me to write and give some thoughts on DotNetOpenAuth. For folks who are new to OpenID I am going to demonstrate how you can implement one in your project with ease.

To get started download the DotNetOpenAuth API and extract the contents from the zip file. The download also includes some samples for you to get you started. Kickstart by creating a new ASP.NET webforms project. I am just using a default template for my application, you can use the one you like or start by creating a new page. Why I am using the default template for ASP.NET webform project? well you get to know later. So now when we are done creating a new ASP.NET webform project, time to add OpenID stuff in the project. Right click References  and select Add Reference. Browse to the bin folder where you have extracted the contents of the downloaded zip file. Select DotNetOpenAuth.dll and click OK.

Changing the web.config:

A minor change in the web.config is required. Find the below lines in your web.config file:

 <authentication mode="Forms"><forms loginUrl="~/Account/Login.aspx"
timeout="2880" /></authentication>

and replace it with:

<authentication mode="Forms"><forms defaultUrl="/default.aspx"

In the above configuration, loginUrl will always point towards to the login page and the defaultUrl will always point towards the page/URL which will be displayed when the authentication is successfull.

Implemeting OpenID support:

To implement OpenID support, open login.aspx page in the design view and then drag the OpenIdLogin from the toolbox on the page just after the default login implementation ends or where you want to have OpenID login. If you are not able to view the control, then you can browse the same dll you have add a reference in the above step.

If you want to implement this manually then register the control at the top of the page and then use it on the page.

Register the control:

<%@ Register Assembly="DotNetOpenAuth" Namespace="DotNetOpenAuth.OpenId.RelyingParty"
TagPrefix="rp" %>

To use the control on the page you can then simply write:

<rp:OpenIdLogin ID="OpenIdLogin1" runat="server"></rp:OpenIdLogin>

All done now and it's time to test our application. Hit F5 and login with your openID. The page rendered in front of you is

Enter your openID and click login. You will be redirected to the official OpenID login page

Enter your password for openID account and after the authentication is successfull you will be re-directed to the default page. Remember the web.config configuration we did!!? If everything goes well you can see your openID name login name on the top of the page.

This is the simplest way to implement openID. You can also implement openID on your ASP.NET MVC project to add some flexibility for you site users. Apart from this you can also download the Visual Studio 2010 template

Download: (542.85 kb)

Related Links:

Currently rated 4.0 by 2 people

URL Routing With ASP.NET 4 - Web Forms

26. June 2010 18:38

.NET Framework ASP.NET C# 

URL Routing was first introduced in .NET framework 3.5 SP1 but MVC has built-in and works pretty decently to create SEO friendly URL and prevents URL hacking. ASP.NET 4.0 is now introduced with a new feature called URL routing with web forms. URL routing help developers to create short and friendly URLs which enhance search engine page ranking. There are few other ways to create short friendly URLs like extension or if you have a physical access to IIS you can have installed URL Rewriter extension for IIS 7 to create short friendly URLs. Hey! not everyone has access to IIS!! So if you don't have the access then also you can re-write the URLs using this new feature in ASP.NET 4.0. 

One thing I would like to mention is that when you create a new ASP.NET web application in Visual Studio 2010, it won't show up with a blank page, but instead build a full applicaton with sample pages with a pretty good design. As you see below I haven't design this page..actually this is a default template when you create a new ASP.NET web application. What I have done here is just put a text box to enter contact ID and a button to get the details from the Adventure Works sample database.


This is a pretty simple interface and now we take a look at some internal work of this web application. My primary focus is on having simple URLs for my application for better search engine optimizations. This application has two main pages apart from the about and other pages that added to the project through the template. The Default.aspx is the main page where we have a field which allow the user to enter the contact ID for the person he want to search. The other page which handles the request and show the details of the contact person is called View.aspx. But this is a really tricky part from a user's perspective as a user will never see this page on the browser address bar while navigating a website. Check the View.aspx design code and check the <asp:SqlDatasource> tags and notice the SelectParameter tag. As I am using a select query with a parameter to populate the grid, the SelectParameter tag further uses <asp:RouteParameter> with route name and route key.

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>" 
        SelectCommand="select Title,FirstName,MiddleName,LastName, EmailAddress from Person.Contact where ContactID=@id">
            <asp:RouteParameter Name="id" RouteKey="id" />

OK! Let's start up what we have on the Default.aspx page. This is the default page and a user will see this page first. Write the below code on the button to redirect the request to route handler. Here I have used a Regex expression to validate if the user enters a numeric ID and not any alphanumeric or alphabet. This check is just a workaround, I recommend you to use a better validation technique.

if((Regex.IsMatch(txt_pid.Text.Trim(), @"\d+")) == true)
          new { id = txt_pid.Text });

So does this URL make any sense? Not at this moment but surely it will after if you have registered your routes in the Global.asax file. My Global.asax file has a method called void RegisterRoutes(RouteCollection Route)

void RegisterRoutes(RouteCollection routes)

The method MapPageRoute accepts some parameters. The first parameter - "Person-Details" you see is the name of the Route which can be any thing you like. The second parameter - "Person/{id}" is the URL which we have generated. In short this is the URL which is visible to the user and outside world, what is happening internally only a developer knows!. The third parameter - "~/View.aspx" is the physical file which actually process the request and return it to the second parameter. The second parameter is the route URL and you can name it what you like except the parameter you are passing, just make sure you use the same parameter name everywhere. In the method void RegisterRoutes(RouteCollection Route) you can register number of route handlers in a single go under void Application_Start method in the Global.asax file.

void Application_Start(object sender, EventArgs e){
// Code that runs on application startup

Once you registered the routes in the Global.asax file, you are done. Time to press F5 and see the action. On the default page enter the ID and hit the Get Details button. The page rendered in front of you / user will be having a clean tidy URL.


 Download: (175.58 kb)

Currently rated 5.0 by 1 person

ASP.NET MVC 2 Released

12. March 2010 14:33

ASP.NET ASP.NET MVC Visual Studio 

Microsoft announced the final release of their second and popular ASP.NET MVC framework. This release comes up with some excellent features. Scott Gu's Blog Series on MVC 2 describes the new features and extensibility of this new release.

To list out some new features include:

According to Scott Gu the final release of VS2010 will have in-built support for MVC 2.

Recommend Reading:

Download ASP.NET MVC 2 final release for Visual Studio 2008 and Release Notes from Microsoft Download Center

 No Rating

Calling ASP.NET Web Service Using Jquery - Part III - Fetch Data From SQL Server

11. March 2010 01:29

ASP.NET Jquery 

My previous two posts on using Jquery for calling ASP.NET web service takes you to the basics of calling a web service using Jquery AJAX. In this last post of the series I will show hot to fetch data from the SQL Server through a web service.

In this example I am going to show on how we can fetch data from SQL Server. I am using pretty well known Adventure Works database for this example. I am using Person.Contact table for this example. I will show on how to fetch data i.e. first name, last name and e-mail address on the basis of the ContactID.
So first, as usual create a normal ASP.NET project and add the required files. Create a new web service, I have named my web service “AdvService.asmx”. You can name your web service as you like. This time we are fetching data from the SQL Server by passing a parameter to the web service method. I am using the very same, basic way of fetching record from the SQL Server. You can also use LINQ here to fetch data.

I have used a delay of few seconds to how the animation, rest in the code is self explanatory. Just passing a parameter and fetching the details of the person from the Adventure Works database.Below are the screenshots for the sample application.

Download: (97.86 kb)

Currently rated 5.0 by 7 people

Calling ASP.NET Web Service Using Jquery - Part II - Passing Parameters

5. March 2010 18:35

ASP.NET Jquery 

In my previous post I have shown with a simple example on how you call an ASP.NET web service using JQuery. In this post I will show how you on how can you pass parameters to the web method and get the result using the web service.
If you have read my previous post, you have seen that we have just called a web method which returns a simple string back to us. In this example, instead of returning a plain simple string back to the client, we will ask the user to enter two numbers and the call the web service which in turn add the two numbers and returns the result back to the client.

First start up with the design of the page. As we are going to add two numbers, we will add a label, textboxes and a button as shown in the below screenshot:

Add a web service to your project as I have described in my previous post. Follow the same steps to add a web service to your project. The only change that you have to make is to add a method which accepts two numbers as parameters and return the sum of the two numbers. For your convenience, the method is as follows.

public int Add(int num1, int num2)
	return num1 + num2;

The script which I am using here to call the web service is the same as I have shown in my previous post, but the data parameter in the ajax function needs to be changed. When we are calling a web service which returns a normal string to us we can set the data parameter to blank. But this is not the case when we have to pass parameters to the web service to return the result. The data parameter in the Jquery ajax script goes something like this:

data: "{'num1': " + $("#txt_num1").val() + ", 'num2': " + ("#txt_num2").val() + "}"

In this parameter the ‘num1’ and ‘num2’ are the name of the parameters in the web service which we have to fulfill if we want the result from the web service. The parameter variable name should always remains the same as defined in the web service method. The parameters and their values are separated by a ‘:’( colon) and a ‘,’ (comma) is used to separate the parameters. The Jquery script $(“txt_num1”).val() will set the value to the parameter and then pass it to the web service method to get the result.

The code for Jquery script to call a web service in this example goes like this:

function CallService() {
                type: "POST",
                url: "Service.asmx/Add",
                data: "{'num1': " + $("#txt_num1").val() + ", 'num2': " + $("#txt_num2").val() + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                error: OnError

            function OnSuccess(data, status) {

            function OnError(request, status, error) {


I have added a bit of CSS to show ajax loading style animation. I am not covering it here but sure I will in the later Jquery posts. In my next post I will cover on how to fetch data from the SQL Server using a web service.

Download: (94.76 kb)

Currently rated 4.8 by 12 people