ASP.NET MVC framework uses the ASP.NET routing engine

URL Routing

Agenda

  • Overview
  • Mapping URL to Controller Action Method
  • Applying Constraints on Route parameters
  • Resolving Namespace Ambiguity
  • Ignoring Routes

URL Routing Overview

The ASP.NET MVC framework uses the ASP.NET routing engine, which provides flexibility for mapping URLs to controller classes. You can define routing rules that the ASP.NET MVC framework uses in order to evaluate incoming URLs and to select the appropriate controller. You can also have the routing engine automatically parse variables that are defined in the URL, and have the ASP.NET MVC framework pass the values to the controller action methods as parameters.

Global URL Routing Defaults:

Routes are initialized in the Application_Start method of the Global.asax file. The following example shows a typical Global.asax file that class RourteConfig.RegisterRoutes which includes default routing logic.

public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// . . .
RouteConfig.RegisterRoutes(RouteTable.Routes);
// . . .
}
}
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: “Default”,
url: “{controller}/{action}/{id}”,
defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
);
}
}

Implementing Routing for Employee Application:

Add following route methods to the Global.asax file

routes.MapRoute(
"Create", // Route name
"Create", // URL with parameters
new { controller = "Employee", action = "Create" } // Parameter defaults
);
routes.MapRoute(
"Edit", // Route name
"Edit/{Id}", // URL with parameters
new { controller = "Employee", action = "Edit" } // Parameter defaults
);
routes.MapRoute(
"Delete", // Route name
"Delete/{id}", // URL with parameters
new { controller = "Employee", action = "Delete" } // Parameter defaults
);

Note:All the entries must be above “Default” route because otherwise it will take precedence and others will not be useful.

Applying Constraints on Route parameters

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{name}/{id}",
defaults: new { controller = "Home", action = "Index", name="test", id = UrlParameter.Optional },
constraints: new { name="[a-z]{5}", id = @"\d{1,8}" }
);

The above route puts a constraint on ID that it should be between 1 and 8 digits only.

Example 2: Overloaded version of MapRoute

routes.MapRoute("Default ",
"{controller}/{action}/{id}",
new RouteValueDictionary { //Default Values
controller = "Home",
action = "Index",
name="test",
id = UrlParameter.Optional },
new RouteValueDictionary { //Contraints
{ "name", "[a-z]{5}" },
{ "id", @"\d{4}" } });

 Resolving Namespace Ambiguity

If we have two HomeController Classes in different namespaces.

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MyDemoApp.Controllers" }
);
//OR
ControllerBuilder.Current.DefaultNamespaces.Add("MyDemoApp.Controllers");

Ignoring Route URL’s

If routes.IgnoreRoute(“Home/Index/123”); is added to RegisterRoutes method

the url: http://localhost:49165/Home/Index/123

will render HTTP Error 404.0 – Not Found

ASP.Net MVC 5./ Filter Overrides

Filter Overrides in ASP.Net MVC 5.X

 

Filter Overrides in ASP.NET MVC 5 are very useful when we are implementing a global or controller level filter and we do not want to apply an action filter on some Action methods in the controller. This feature is useful for removing the headache of applying filters for each and every action where we need to exclude only a few actions. For following five types of filters available with MVC:

1.Authentication filters
2.Authorization filters
3.Action filters
4.Result filters
5.Exception filters

We have five type filter overrides corresponding to this:
– OverrideAuthenticationAttribute
– OverrideAuthorizationAttribute
– OverrideActionFiltersAttribute
– OverrideResultAttribute
– OverrideExceptionAttribute

We can mark any action method with an override filter attribute that essentially clears all filters in an upper scope (in other words controller level or global level).

Example: In the following example, the Authorize Filter is applied at the controller level.So, all the action methods of the Home controller can be accessed by the Admin user only. Now I want to exclude the Authorize Filter from the “About” method.

So in this case we can mark this “About” method with the “OverrideAuthorization” attribute. Now all the action methods of the home controller can be accessed by the Admin user except the “About” method. We can access the “About” action method without any authorization.

[Authorize(Users=”John”)]
     public class HomeController : Controller
              { public ActionResult Index() 
                                {
                                  return View(); 
                                        } 
                           [OverrideAuthorization]
                           public ActionResult About() 
                                              { 
                                                      return View(); 
                                                 }
                                                     } 

Note: The OverrideAuthorizationAttribute does not work properly with MVC version 5.0 due to some internal bug. This bug was resolved in MVC version 5.1 (preview).

Cancelling Filter Execution:

1. You can cancel filter execution in the OnActionExecuting methods by setting the Result property to a non-null value.

a. Any pending OnActionExecuted and OnActionExecuting filters will not be invoked
b.Invoker will not call the OnActionExecuted method for the canceled filter or for pending filters.
c.The OnActionExecuted filter for previously run filters will run.
d.All of the OnResultExecuting and OnResultExecuted filters will run.

2. You can cancel filter execution in the OnResultExecuting methods by setting the Cancel property true.
a. Any pending OnResultExecuted and OnResultExecuting are canceled and blank o/p is rendered to browser.
b. The OnResultExecuted filter for previously run filters will run.

 public class Log2Attribute : ActionFilterAttribute

                      {

                          public override void OnActionExecuting(ActionExecutingContext filterContext)

                               {

                                 //filterContext.Result = new EmptyResult();
                                 Trace(“On Action Executing”, filterContext.RouteData);

                            }

                  public override void OnActionExecuted(ActionExecutedContext filterContext)
                               {

                                Trace(“On Action Executed”, filterContext.RouteData);

                            } 
                 public override void OnResultExecuting(ResultExecutingContext filterContext)

                        {

                            filterContext.Cancel = true;
                                  //filterContext.HttpContext.Response.Write(“Advertisement <hr>”);
                                   Trace(“On Result Executing”, filterContext.RouteData);
                        }

             public override void OnResultExecuted(ResultExecutedContext filterContext)
                        {

                            //filterContext.HttpContext.Response.Write(“<hr>Advertisement”);
                             Trace(“On Result Executed”, filterContext.RouteData);

                      }
               public void Trace(string methodName, RouteData routeData)
                     {

                          string colName, actionName;

                          colName = routeData.Values[“controller”].ToString();
                             actionName = routeData.Values[“action”].ToString();
                         string str = string.Format(“2 – Method Name={0}, Controller Name={1},Action={2}”, methodName, colName, actionName);
                         System.Diagnostics.Trace.WriteLine(str);
                        HttpContext.Current.Response.Write(“<br>” + str + “<br>”);

                      } 

                 }

self paced learning on ASP.NET MVC 5.2

 

MVC-Action Selectors

Action Selectors HttpGet and HttpPost

Action Selectors

When the MVC Framework is selecting one of the controller public methods to invoke as an action, it will use any action selector attribute that might be present to define the correct action to invoke.

1. ActionName

2. AcceptVerbs

  • HttpPost
  • HttpGet

ActionName: When we apply this to a controller action it will specify the action name for that method. For the Index method we have bellow we no longer reach this method as action name “Index”. We have to reach this method as “Start”. (http://localhost:123/Home/Start)

[ActionName(“Start”)]
public ActionResult Index()
{
ViewBag.Message = “Welcome to Deccansoft!”;
return View();
}
Note: A view by name “Start” must be added. Index view will not work.

*Can be used if the URL has “_” or “-“ and method doesn’t have the same.

*Also useful when method names and parameters are same for both HTTPGet and HTTPPost.

Also
[ActionName(“GetCSVFileContent”)]

public ActionResult GetCSV()
{
string csv = CreateCSV();
return new ContentResult() { Content = csv, ContentEncoding =
System.Text.Encoding.UTF8, ContentType = “text/csv” };
}

AcceptVerbs: Http verbs allow us to reach a particular action we can say action method is reachable with:

1. [HttpGet] or [AcceptVerbs(HttpVerbs.Get)]

2. [HttpPost] or [AcceptVerbs(HttpVerbs.Post)]

3. [RequireHttps] – Forces the Http request to be resent over Https.

HttpGet: Only get request will be served by action method.

[HttpGet]
public ActionResult LogOn()
{
return View();
}

HttpPost: Only post request will be served by the action method.

In View: @{ Html.BeginForm(); }

<input type=”submit” value=”Submit” /> @{ Html.EndForm(); }

In Controller:

[HttpPost()]

public ActionResult Index(FormCollection col)

{
ViewBag.Greetings1 = “Posted”;
return View();
}

 


Learn Complete ASP.NET MVC 5.2