Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
3 Dec 2014 1  
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:
       filters.Add(new ExecutionTrace());
  4. Create a class for Execution which is inherited from ActionFilterAttribute. Add the below code.

Creating Custom Action Filter

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.

 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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here