Dec052009

MVC Case Sensitivity & Action Names & NonAction Attribute

Today, it was the first class of our free ASP.NET MVC course. I was talking about URLs not being case sensitive. So that for example if you have the request “Home/About” this goes to HomeController and About action, as well as hOmE/AbOUT is going to the same controller and same action method.
One of the students ask me, what will happen if we have 2 about action methods in the same controller with different cases such as:

public class HomeController:Controller
{
....
    public ViewResult About()
    {
        return View();
    }

    public ViewResult aBOut()
    {
        return View();
    }
}

If you write the code above, and try to run the app, and call Home/About, here is the error message you will get:

image

The framework can’t determine which ‘about’ function to call, and throws the exception telling that the call is ambiguous. Of course one way to fix this problem is to change the action name. If for some reason you don’t want to change the action name, and one of these function is not an action, then you can decorate this non action method with NonAction attribute. Example:

[NonAction]
public ActionResult aBOut()
{
   return View();
}

So now this function is not anymore an action method that will handle the web requests. What is NonAction attribute?
It is an attribute that derives from ActionMethodSelectorAttribute. When you derive from this attribute you can override IsValidForRequest function, and return false, to refuse to serve as an action. If you check the MVC source code, here is the code for NonAction attribute:

[AttributeUsage(AttributeTargets.Method, 
AllowMultiple = false, Inherited = true)] public sealed class NonActionAttribute : ActionMethodSelectorAttribute { public override bool IsValidForRequest(ControllerContext
controllerContext, MethodInfo methodInfo) { return false; } }
 

This code is refusing to act as a request. So you can use this NonAction attribute on any of your public functions inside a controller to make them not web accessible.



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Add comment