65.9K
CodeProject is changing. Read more.
Home

Handling Unknown Actions in ASP.NET MVC

starIconstarIconstarIconstarIconstarIcon

5.00/5 (5 votes)

Aug 16, 2009

CPOL

1 min read

viewsIcon

37953

In this article, I will explore handling unknown actions. A Controller.HandleUnknownAction method gets called when a controller cannot find an action method that matches a browser request.

Introduction

A Controller.HandleUnknownAction method gets called when a controller cannot find an action method that matches a browser request.

Background

In this article, I will explore handling unknown actions. A Controller.HandleUnknownAction method gets called when a controller cannot find an action method that matches a browser request. I have implemented the following method in my previous article: Implementing HTTP File Upload with ASP.NET MVC.

Here is the syntax in C#:

protected virtual void HandleUnknownAction(string actionName) 

Here is a FileUploadController class that implements HandleUnknownAction as shown below:

[HandleError]
public class FileUploadController : Controller 
{ 
    public ActionResult FileUpload() 
    {
        return View(); 
    } 
    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult FileUpload(HttpPostedFileBase uploadFile) 
    { 
        if (uploadFile.ContentLength > 0) 
        { 
            string filePath = 
               Path.Combine(HttpContext.Server.MapPath("../Uploads"), 
                            Path.GetFileName(uploadFile.FileName)); 
            uploadFile.SaveAs(filePath); 
        } 
        return View(); 
    } 
    protected override void HandleUnknownAction(string actionName) 
    { 
        actionName = "FileUpload";
        this.View(actionName).ExecuteResult(this.ControllerContext); 
    } 
}

The above example displays the FileUpload view when a request for the FileUpload action is made on the controller. If there is no matching view, then the FileUpload controller HandleUnknownAction() method is invoked. I have hard coded the FileUpload view so that if the browser request does not match the FileUpload, it will explicitly call the FileUpload action. Here is the view with the unknown action:

Notice that the controller does not have the UploadToGoogle action, but our HandleUnknownAction() method is invoked and it explicitly calls the FileUpload action.

Summary

A Controller.HandleUnknownAction method gets called when a controller cannot find an action method that matches a browser request. Therefore, in your controller class, you don’t need to explicitly code an action method for each view.