Click here to Skip to main content
15,892,517 members
Articles / Web Development / ASP.NET

ASP.NET MVC controller action with Interceptor pattern

Rate me:
Please Sign up or sign in to vote.
4.40/5 (4 votes)
2 Oct 2012CPOL8 min read 67.8K   924   24  
This article is to demonstrate interceptor pattern with MVC controller action, and so action can be intercepted in controller classes without using action filters.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcCallInterceptors.Controllers;
using MvcCallInterceptors.Interceptors;
using MvcCallInterceptorsDemo.Models;

namespace MvcCallInterceptorsDemo.Controllers
{
    public class MyHomeAccountController : BaseMvcController
    {
        //
        // GET: /MyHome/

        [ActionInterceptor("Home", "Index")]
        public object Index(InterceptorParasDictionary<string,object> paras, object result)
        {
            (result as ViewResult).ViewBag.Message = (result as ViewResult).ViewBag.Message + " Hey, I have intercepted.";
            return result;
          
            /*//verify for error whether HandleError filter gets called.
            object s = null;
            (result as ViewResult).ViewBag.Message = s.ToString() + (result as ViewResult).ViewBag.Message + " Hey, I have intercepted.";
            
            ViewBag.Message = s.ToString();
            return result;*/
        }


        [ActionInterceptor(InterceptionOrder.Before, "Account", "LogOn")]
        public void SubmitLogOn(InterceptorParasDictionary<string, object> paras, object result)
        {
            if (paras.Count > 0)
            {
                (paras["model"] as LogOnModel).UserName = "***" + (paras["model"] as LogOnModel).UserName;
            
            }            
            
        }

        [ActionInterceptor(InterceptionOrder.After, "Account", "LogOn")]
        public object MyLogOn(InterceptorParasDictionary<string, object> paras, object result)
        {
            if (paras.Count == 0)
            {
                return View("MyLogOn");
            }
            else
            {
                return result;
            }
        }

        protected override string View
        {
            get { return "MyHome"; }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Like to dream on long drive and falling asleep on short drive..!

Comments and Discussions