Asp.Net MVC How to log all actions being called - asp.net-mvc

I need to be able to log all actions that are called from my asp.net mvc application. How and what would be the best way to achieve this? Where I log it to whether it be the console or log file doesn't matter.

You could create your own class which inherits from ActionFilterAttribute and then override the OnActionExecuting method.
Example
public class LogActionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = filterContext.RequestContext.RouteData.Values["Controller"];
var action = filterContext.RequestContext.RouteData.Values["Action"];
//
// Perform logging here
//
base.OnActionExecuting(filterContext);
}
}
public class HomeController : Controller
{
[LogAction]
public ActionResult Index()
{
return View();
}
}
Hope this helps!

Credit HeyMega for their answer. Here's an example of an expanded implementation I arrived at in MVC5.
public class LogActionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = filterContext.RequestContext.RouteData.Values.ContainsKey("Controller") ? filterContext.RequestContext.RouteData.Values["Controller"].ToString() : null;
var action = filterContext.RequestContext.RouteData.Values.ContainsKey("Action") ? filterContext.RequestContext.RouteData.Values["Action"].ToString() : null;
var area = filterContext.RequestContext.RouteData.DataTokens.ContainsKey("Area") ? filterContext.RequestContext.RouteData.DataTokens["Area"].ToString() : null;
var user = filterContext.RequestContext.HttpContext.User.Identity.GetUserId();
Task.Run(() => Generic().AreaActionLog(user, area, controller, action));
base.OnActionExecuting(filterContext);
}
}
I chose to separate the method doing the actual logging into a separate process, if anything goes wrong with the Database interaction, or the DB interaction takes several seconds, the UI is uninterrupted.
You can then decorate the entire controller with [LogAction] attribute like so.
[LogAction]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Contact()
{
return View();
}
}
Or selectively apply the attribute by decorating individual methods:
public class HomeController : Controller
{
[LogAction]
public ActionResult Index_Logs_Things()
{
return View();
}
}
Hope this helps someone.

You could try Audit.NET library with its Audit.MVC and the different data providers to store the logs on files, eventlog, sql, redis, mongo, and much more.
With the MVC extension you just need to decorate your controllers or actions with an attribute:
[Audit]
public class HomeController : Controller
{ ... }
Execute a static configuration to set the output of your logs:
Audit.Core.Configuration.Setup()
.UseFileLogProvider(_ => _
.Directory(#"C:\Logs"));
And it will provide the infrastructure to log the interactions with your MVC application.

Related

ASP.NET MVC - Routing Structure

I have an ASP.NET MVC 4.5 app. In this app, I have two controllers: Parent and Children. The look something like this:
[RoutePrefix("dashboard/parents")]
public partial class ParentsController : Controller
{
public ActionResult Index()
{
return View();
}
[Route("add")]
public ActionResult Add()
{
return View();
}
}
[RoutePrefix("dashboard/children")]
public partial class ChildrenController : Controller
{
public ActionResult Index()
{
return View();
}
[Route("add")]
public ActionResult Add()
{
return View();
}
}
At this time, these controllers work how I want. However, in my ChildrenController, I want to add something like an overload to the add route. In other words, I'd like for the user to be able to visit: /dashboard/parents/{parentId}/children/add. This URL would be used to add a child to a specific parent. My question is, how do I update my controllers to allow for this type of scenario?
thank you!
I think what you are looking for the is "~" to override your default routeprefix.. The following example is taken from the asp.net website which tells you how to accomplish the task.
[RoutePrefix("api/books")]
public class BooksController : ApiController
{
// GET /api/authors/1/books
[Route("~/api/authors/{authorId:int}/books")]
public IEnumerable<Book> GetByAuthor(int authorId) { ... }
// ...
}

Why doesn't my action filter get called?

The code:
public class TheFilter : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
}
}
public class NotesController : BaseController
{
[TheFilter]
[HttpPost]
public ActionResult Edit(EditViewModel viewModel)
{
viewModel.Note.Modified = DateTime.Now;
viewModel.Note.ModifiedBy = User.Identity.Name;
var noteTable = StorageHelper.GetTable<Note>(viewModel.PageMeta.DataSourceID);
noteTable.AddOrUpdate(viewModel.Note);
return Home();
}
}
When I debug on return Home() and step through then I bypass the action filter and go straight to the Home() method.
Am I declaring the action filter correctly?
Make sure you're implementing
System.Web.Mvc.ActionFilterAttribute
and not
System.Web.Http.Filters.ActionFilterAttribute
They both have OnActionExecuting and OnActionExecuted Methods, so it can be a little deceiving.
Maybe you don't reach the method directly but call Edit action from other action?
put the filter on the controller and see what happens.
I was also facing the same issue I was just missing the override keyword before the OnExecuting method. It started working after adding override keyword.
Use the Onexecuting not onExecuted
public override void OnActionExecuting(ActionExecutingContext filterContext)

ControllerContext is null and BaseController.OnActionExecuting() not called when using Html.Action

We use a BaseController to cache basic authentication information before every action executes:
public abstract class BaseController : Controller
{
protected bool IsLoggedIn { get; set; }
protected string Username { get; set; }
...
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
var identity = base.User.Identity;
this.IsLoggedIn = identity.IsAuthenticated;
this.Username = identity.Name;
...
}
}
And our child controller has a actions for the main page (Index) and a partial view (GetNavigation):
[Authorize]
public partial class CollaborationController : BaseController
{
[HttpGet]
public virtual ViewResult Index()
{
var viewModel = this.MakeViewModel<FullPageViewModel>();
return this.View(MVC.Collaboration.Views.Index, viewModel);
}
[HttpGet]
public virtual PartialViewResult GetNavigation()
{
var viewModel = NavigationViewModel.Make(this.User);
return this.PartialView(MVC.Collaboration.Views.Navigation, viewModel);
}
}
And the partial view is rendered directly with Html.Action():
#Html.Action(MVC.Collaboration.GetNavigation())
Seems like it should work, but BaseController.OnActionExecuting does not get called. And I can't even call it directly because this.ControllerContext and base.User are both null. I also tried subclassing ActionFilterAttribute, but its OnActionExecuting method doesn't get called, either.
I know this is an old question but here is how I handle this. In my child controller I create the OnActionExecuting method and call the base controller from there.
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}
At least sort-of answered my own question:
Substituting
#Html.Action("GetNavigation", "Collaboration")
for
#Html.Action(MVC.Collaboration.GetNavigation())
fixes it. MVCContrib's syntax seems to be the culprit, anyone know why? Even better, anyone know a work-around that lets me avoid those nasty, non-refactoring-safe, magic strings?

What is the basepage equivalent in MVC

In my ASP.Net web sites I have the following code that I am able to use site-wide.
How do I do the same in ASP.Net MVC2?
public class BasePage : Page
{
public BasePage()
{
this.PreInit += new EventHandler(BasePage_PreInit);
}
/// <summary>Every page executes this function before anything else.</summary>
protected void BasePage_PreInit(object sender, EventArgs e)
{
// Apply Theme to page
Page.Theme = "Default";
}
public bool IsSiteAdmin(string userName)
{
if (System.Web.Security.Roles.IsUserInRole(userName, "SiteAdmin1"))
return true;
return false;
}
}
Not sure how themes fit into MVC (not very well I suspect), but in general you just need to create a base controller class.
public class BaseController : Controller
and then derive all your controllers off this base.
public class HomeController : BaseController
That way, you can have common functionality available to all controllers. eg your IsSiteAdmin method.
As zaph0d said, you want to override the Controller class. There are several "events" you can override when creating your own Controller class. A list of those would be here:
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller_members.aspx
Here's what you might want to do. Note that I have no idea what Page.Theme is or does.
public class BaseController : Controller
{
protected string Theme { get; set; }
protected override void OnActionExecuting(ActionExecutingContext context)
{
Theme = "Default";
}
public bool IsSiteAdmin(string userName)
{
return System.Web.Security.Roles.IsUserInRole(userName, "SiteAdmin1");
}
}
MVC has master pages and views. It sounds like you want your Controller to have some base logic in it instead of your page. In your controller you can select a different master page when rendering your views, based on your condition, if you want.

ASP.NET MVC RequireHttps

How do I use the ASP.NET MVC 2 Preview 2 Futures RequireHttps attribute?
I want to prevent unsecured HTTP requests from being sent to an action method. I want to automatically redirect to HTTPS.
MSDN:
RequireHttpsAttribute
RequireHttpsAttribute Members
RequireHttpsAttribute.HandleNonHttpsRequest Method
How do I use this feature?
I think you're going to need to roll your own ActionFilterAttribute for that.
public class RedirectHttps : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if (!filterContext.HttpContext.Request.IsSecureConnection) {
filterContext.Result =
new RedirectResult(filterContext.HttpContext.Request.Url.
ToString().Replace("http:", "https:"));
filterContext.Result.ExecuteResult(filterContext);
}
base.OnActionExecuting(filterContext);
}
}
Then in your controller :
public class HomeController : Controller {
[RedirectHttps]
public ActionResult SecuredAction() {
return View();
}
}
You might want to read this as well.
My guess:
[RequireHttps] //apply to all actions in controller
public class SomeController
{
//... or ...
[RequireHttps] //apply to this action only
public ActionResult SomeAction()
{
}
}

Resources