ASP.NET MVC twitter/myspace URL style routing

February 15, 2010

(1) Comment

Disclaimer : This tutorial is meant for beginners and for anyone who find it useful. The main purpose of this post to keep everything i find useful for future reference for myself and for others.


With ASP.Net MVC url routing feature its also desirable to have twitter/myspace url style routing for your application. Its also give simple and shorter personalize url for your user.

There is 2 steps to accomplish this, first is to define the url route in routing tables and second is to define route constrains.

Step 1 : Add following route map in Global.asax below your default routes to handle personalize user url


// to handle personalize user url
routes.MapRoute
(
"user",
"{url}",
new { controller = "Link", action = "url", url = "" }
);

In the above code I let my url method in Link controller handle the request , basically the method will check the supplied user is exist or not and do whatever necessary .

Now you need edit your default route because when you try invoke user url like http://yoursite.com/user it will processed by the default url and you will get  The resource cannot be found error. So we need add url constraints to our default url so that it only processed the non user url. To do that we need create Custom Route Constraints , see the following blog post by Guy Burstein. I get the following code there , create the following class in your project..


using System.Web.Routing;
using System.Web;
public class FromValuesListConstraint : IRouteConstraint
{
private string[] _values;

public FromValuesListConstraint(params string[] values)
{

this._values = values;

}

public bool Match(HttpContextBase httpContext,Route route,string parameterName,
RouteValueDictionary values,RouteDirection routeDirection)
{
// Get the value called "parameterName" from the
// RouteValueDictionary called "value"

string value = values[parameterName].ToString();

// Return true is the list of allowed values contains
// this value.

for (int i = 0; i < _values.Length; i++)
if (_values[i].Equals(value))
return true;

return false;
}

}

Now we are ready to modify our default route , change your default route to something similar to following code


routes.MapRoute
(
"Default",                                              // Route name
"{controller}/{action}/{id}",                           // URL with parameters
new { controller = "Home", action = "Index", id = "" },  // Parameter defaults
new { controller = new FromValuesListConstraint("Home", "Account","Link") }
);

The parameters values is to tell the route engine which url should be handle by this route definition. Now your personalize user url should work accordingly. If you the url does’t work get ASP.NET Routing Debugger from Phil Haacked and test your urls.

BALA SINGAM

, , , , ,


1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

ASP.NET MVC Release Candidate 1

January 29, 2009

(0) Comments

Finally ASP.Net MVC Release Candidate 1 is ready for download before the version 1 expeceted to be release next month. Its been more than a year since CTP release on 2007-12-10 and i been try it out since preview 5 release.

For beginners, Stephen Walther have posted excellent articles and tutorials to get started. If you already following ASP.Net MVC for sometimes then you should read these blog posts on RC 1.

BALA SINGAM

, ,


1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Running ASP.Net MVC on IIS 5.1

January 23, 2009

(3) Comments

When i start to create my first ASP.Net MVC application and try run it on IIS 5.1 ( Win XP) i faced problems as it could not run as its run on the project run mode. There was 2 particular problem , first the home page does not apply the CSS or formating and second problem u cannot navigate to other pages because the controller throw “Page cannot be found” error.

CSS and formatting not applied

First problem CSS and formating not applied.

Controller throw error

Second problem controller throw “Page cannot be found” error

I tried few solutions that i found after googling before but non of them work and leave this problem for while. This including  doing some configuration changes in IIS to add .MVC handler but that’s not worked either.  Today i googled again to find solution for this and found a solution given by Ajit Shekhawat. You can access the solution page at CodeProject.

There is 2 things suggested by Ajit Shekhawat to solve this problem , i tried and its worked for me :) . First step is to modify Page_Load() function on Default.aspx.cs file according the code below .

public void Page_Load(object sender, System.EventArgs e)
{
if (Request.ApplicationPath == “”)
{
HttpContext.Current.RewritePath(Request.ApplicationPath + “home.aspx”);
}
else if (Request.ApplicationPath == HostingEnvironment.ApplicationVirtualPath)
{
HttpContext.Current.RewritePath(Request.ApplicationPath + “/home.aspx”);
}
else
{
HttpContext.Current.RewritePath(Request.ApplicationPath);
}
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
}

Second step is to modify RegisterRoutes function on Global.aspx.cs as below , (added “.aspx” as extension to controller)

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.MapRoute(“Default”, “{controller}.aspx/{action}/{id}”,
new { controller = “Home”, action = “Index”, id = “” });
}

These modification must be done on project file and publish your project on IIS 5.1 and its should work as its works for me :) . The only drawback of these changes is your home controller would have .aspx extension on it and looks weird, see url below.

http://localhost/mvc/Home.aspx/About

Credit for this solution must go to Ajit Shekhawat and original solution can be found at CodeProject

Update

Official solution from Microsoft can be found at ASP.Net page.

BALA SINGAM

,


1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Etho orru post….

December 22, 2008

(0) Comments

Its just another day at work …. mani 4.23pm achi , tukkam tukkam ma varethe verra…. innum SSIS velai senji mudikele. GRE exam ke verra padikenum ( book vanggi oru month kude achi  annal innum orru chapter kude padichi kileke) , exam on 31st december :( Neraiya velai pending le irukke ethuvum seiya mood ille.

Need to prepare my Statement of purpose for the masters application , anthe eleve verra prepare pennenum , atherkum idea ille. Chinna vaise le irunthe ellathiyum last minute lei seirethe nan vanggithe vanthe varam achi. Evele time iruthalum anthe kadi minute le than velei ye nadekum. My biggest weakness is time management. I wasted a lot of time in my life dreaming :) .

Valkeile neraiya seiyenum , achieve pennenum assai , neraiya kathekenum assai annal because my bad time management ellamme half way stop airum. Mukiyumma rumba neram tunggiye vinaikireven ( and lately its getting worse). I only have 8 days left to study for my GRE exam and i have alot to cover. I also need write letter to my past university (where i done my BSc) to request to send official transcript to the university that i intend to apply. Ithe ennoru thalei valli. Universities in Malaysia not familiar of this procedure sending official transcripts onbehalf of student.

When i call the CalState LA earlier this month to explain my situation this was the response from the person who answer my call

“No , your not the first person applying from Malaysia , we have been receiveing students from Malaysia and they able to request their University to send official transcripts and you should too”.

I know i gonna have hard time to convince my university to do this for me , knowing their attitude very much. Anthe Murugan orru nalle valiye kathenum.

Inthe paracheneigal gap le blog penneve time ille ( actually time irukke annal manage penne terile ). Initially I planned to fill this blog with technical posting , annel kalam pokkal athe kunjem mission imposibble mathiri peikithe irukke , cause its take more time to prepare the materials.

Manasene nimthiya blog penne kude vidematherangge (athe kule customer kithe irunthe call , ethavethe sethei pennithe nambe uyire vanggevangge :(   ).

Eppediyo inthe year end ke vare pothe and next new year yum varre pothe, so new year sonnale new year resolution irukenum ( achieve pennerumo illayo itu belakang cerita ). So nanum 3 visiyum en year 2009 resolution vichiruken.

First resolution , by this time of next year I must enroll for masters at any one of university in United State most likely in California. Second ASP.Net MVC mastered pennenum , means atleast have one online website based on ASP.Net MVC. Kadesi resolution , chinna vaisele irunthe rumba asai guitar kathekenum ne. Recently varanam aiyerum movie light the spirit back in me and most important thing last nite i have found a channel in YouTube by itsSoldier . He is tamilan and currently in california and play guitar excellent!

To end this rambling post i have post one of performance from itsSoldier

YouTube Preview Image

BALA SINGAM

, , , , , , ,


1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 4.00 out of 5)
Loading ... Loading ...