HandleUnknownAction in ASP.NET MVC – Be Careful

One of my team members was showing me some code in HandleUnknownAction based upon sample code in the online documentation. Per the documentation:

 

“The following example shows how to render views that do not have a matching ActionResult method. For example, if you have a Details.aspx view but no corresponding method exists that returns an ActionResult instance, the following example displays the Details view when a request to for the Details action is made on the controller. If there is no matching view, the error page displays a message.”

 

protected override void HandleUnknownAction(string actionName)

{

    try

    {

        View(actionName).ExecuteResult(ControllerContext);

    }

    catch (InvalidOperationException ieox)

    {

        ViewData["error"] = “Unknown Action: \”" +

            Server.HtmlEncode(actionName) + “\”";

        ViewData["exMessage"] = ieox.Message;

        this.View(“Error”).ExecuteResult(this.ControllerContext);

    }

}

 

The only problem with this example is that it does not take into account attributes, like the ActionMethodSelectorAttribute, that can decide based on runtime information whether an action can fulfill a request. So, it may not be that the action does not exist, but that it is not supposed to respond to the request based on the context of the request.

For example, if I use the AcceptVerbsAttribute, an example of ActionMethodSelectorAttribute, to do something as simple as this on my HomeController:

 

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult DisplayOnlyViaPost()

{

    return View();

}

 

The DisplayOnlyViaPost View will not be displayed via the DisplayOnlyViaPost Action when someone types the URL in a browser ( HTTP GET Request ) – http://…/Home/DisplayOnlyViaPost.

Unfortunately, the HandleUnknownAction code above will kick in and notice that indeed the DisplayOnlyViaPost View does exist. Therefore it goes ahead and displays the view, undermining the use of our AcceptVerbsAttribute on the original action. Not good :)

Just something I noticed that you may want to be careful of if you are using similar code in HandleUnknownAction.

 

David Hayden

 

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>