Click here to Skip to main content
15,912,977 members
Articles / Web Development / HTML
Tip/Trick

Implementing Combination of Forms and User AD Name Authentication With Tracing in MVC5

Rate me:
Please Sign up or sign in to vote.
3.75/5 (4 votes)
3 Dec 2014CPOL1 min read 12.1K   2   2
Implementing Combination of Forms and Windows user identity authentication with Tracing in MVC5

Introduction

In this tip, I am going to explain about MVC Custom Action filter tracing while viewing site.

Creating Custom Action Filter Tracing

An action filter consists of logic that runs directly before or directly after an action method runs. You can use action filters for logging, authentication, output caching, or other tasks.

You implement an action filter as an attribute that inherits from the ActionFilterAttribute class.

ActionFilterAttributeClass contains four methods:

  • OnActionExecuting()
  • OnActionExecuted()
  • OnResultExecuted()
  • OnResultExecuting()

You override the OnActionExecuting() method if you want your logic to run before the action method. You override the OnActionExecuted() method if you want your logic to run after the action method. After you define an action filter, you can use the attribute to mark any action methods that you want the filter to apply to.

Steps to create are listed below:

  1. Select new Project in Visual Studio and select under C# web application
  2. Check MVC application and select individual authentication
  3. Go to Appstart folder and open FilterConfig.cs and add the below code:
    C#
    filters.Add(new ExecutionTrace());
    
  4. Create a class for Execution which is inherited from ActionFilterAttribute. Add the below code.

Creating Custom Action Filter

C#
public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            string path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString() 
            + @"\Logs.txt";
            string data = ":OnActionExecuted:";
            data = data + Environment.NewLine+Environment.NewLine;
            data = data + "controller:" + filterContext.Controller.ToString().
            Replace("CustomActionFilter.Controllers.", "");
            data = data + Environment.NewLine;
            data = data + "Action: " + 
            filterContext.ActionDescriptor.ActionName;
            data = data + Environment.NewLine;
            data = data + "IP Address :" + 
            filterContext.HttpContext.Request.UserHostAddress;
            data = data + Environment.NewLine;
            data = data + "Date Time:" + 
            filterContext.HttpContext.Timestamp.ToString("MM/dd/yyyy HH:MM:ss");
            data = data + Environment.NewLine;
            data = data + "Controller Name:" + 
            filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            data = data + Environment.NewLine + Environment.NewLine;
            File.AppendAllText(path, data);

            base.OnActionExecuted(filterContext);
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string path = AppDomain.CurrentDomain.GetData
            ("DataDirectory").ToString() + @"\Logs.txt";

            string data = ":OnActionExecuting:";
            data = data + Environment.NewLine + Environment.NewLine;
            data = data + "controller:" + 
            filterContext.Controller.ToString().Replace
            ("CustomActionFilter.Controllers.", ""); ;
            data = data + Environment.NewLine;
            data = data + "Action Name:" + filterContext.ActionDescriptor.ActionName;
            data = data + Environment.NewLine;
            data = data + "Controller Name:" + 
            filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            data = data + Environment.NewLine + Environment.NewLine;
            File.AppendAllText(path, data);
            base.OnActionExecuting(filterContext);
        }
      
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            string path = AppDomain.CurrentDomain.GetData
            ("DataDirectory").ToString() + @"\Logs.txt";
            string data = ":OnResultExecuted:";
            data = data + Environment.NewLine + Environment.NewLine;
            data = data+"controller:" + 
            filterContext.Controller.ToString().Replace
            ("CustomActionFilter.Controllers.", "");
            data = data + Environment.NewLine;
            data = data + "Result Type:" + 
            filterContext.Result.ToString().Replace("System.Web.Mvc.", "");
            data = data + Environment.NewLine;
            data = data + "Route Handler:" + 
            filterContext.HttpContext.CurrentHandler.ToString();
            data = data + Environment.NewLine + Environment.NewLine;
            File.AppendAllText(path, data);
            base.OnResultExecuted(filterContext);
        }

Authenticate User With AD DomainName

For performing authentication in Application_BeginRequest(), paste the following code in Global.asax.

C#
protected void Application_BeginRequest()
       {
           string path = AppDomain.CurrentDomain.GetData
           ("DataDirectory").ToString() + @"\Logs.txt";
           string data = ":Application Begin Request:";
           try
           {
               if (System.Security.Principal.WindowsIdentity.GetCurrent().
               Name.ToUpper().StartsWith("YOUR_DOMAIN_NAME\\") )
               {
                   data = data + Environment.NewLine;

                   data = data + "Time Stamp: " +
                   DateTime.Today.ToString("MM/dd/yyyy HH:MM:ss");
                   data = data + Environment.NewLine;
                   data = data + System.Security.Principal.WindowsIdentity.GetCurrent().Name;
               }
               else
               {
                   data = data + Environment.NewLine;

                   data = data + "Time Stamp: " +
                   this.Context.Timestamp.ToString("MM/dd/yyyy HH:MM:ss");
                   data = data + Environment.NewLine;
                   data = data + "Throwing 400";

                   throw new HttpException(400, "Bad Request");

               }
               data = data + Environment.NewLine + Environment.NewLine;
               File.AppendAllText(path, data);
           }
           catch (Exception ex)
           {
               data = data + Environment.NewLine;
               data = data + "Exception:" + ex.Message;
               data = data + Environment.NewLine;
               data = data + "Redirect to: NotFound.html";
               File.AppendAllText(path,data);

               this.Context.Server.Transfer("NotFound.html");
           }
       }

Application_BeginRequest() event is raised at every request handled by web application.

Replace your domain in place of "YOUR_DOMAIN_NAME" with your AD DOMAIN NAME.

If User is not in to AD Domain, it automatically raises 400 badrequest and transfers to NotFound.

License

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


Written By
Software Developer Nichebees
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralUseful info on filters but not exactly what I was hoping for Pin
Tim Grindley4-Dec-14 2:27
Tim Grindley4-Dec-14 2:27 
GeneralMy vote of 2 Pin
lemravec3-Dec-14 7:46
lemravec3-Dec-14 7:46 
misleading title

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.