How do I register a global message handler in a MVC application?
I tried registering it in my Global.asax.cs, but this handler never gets called whenever I access any of my endpoints in all my controllers that inherit from System.Web.Mvc.Controller.
However, it does get called when I access routes all my controllers that inherit from System.Web.Http.ApiController.
This is what I put in my Global.asax.cs:
protected void Application_Start()
{
//other initializing stuff here
**GlobalConfiguration.Configuration.MessageHandlers.Add(new AuthenticationHandler());**
}
I believe you're looking for Filters. You could build something like this:
public class MyAuthorizationFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
// do your work here
}
}
and then add it to the global filters list in Application_Start:
GlobalConfiguration.Configuration.Filters.Add(new MyAuthorizationFilter());
Related
I'm using Elmah for logging exceptions on my MVC application using Alex Beletsky's elmah-mvc NuGet package.
The application registers some global filters, applied on each action called.
Is there a way to prevent some of those filters from being applied when calling the Elmah.Mvc.ElmahController error log page (foo.com/elmah) ?
A test like below works, of course, but I'm looking for a more elegant way that would not involve modifying the filter (nor the source code from Elmah / Elmah MVC). Is it even possible ?
public class FooAttribute : FilterAttribute, IActionFilter
{
// ...
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.Controller is ElmahController)
{
return;
}
// do stuff
}
}
I know that attributes can't be added or removed at runtime.
I thought of wrapping the ElmahController in a new one where I could add an exclusion filter, but I'm not sure how (if possible) to change the web.config to reference this wrapper instead of the original controller.
You could register your global filters through a custom IFilterProvider:
public class MyFilterProvider : IFilterProvider
{
public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
if (controllerContext.Controller is ElmahController)
{
return Enumerable.Empty<Filter>();
}
return ... the collection of your global filters
}
}
and in your Application_Start instead of calling:
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
you would call:
FilterProviders.Providers.Add(new MyFilterProvider());
I have a .Net MVC web application (Not WebAPI), and I want to intercept all calls to the web app before they reach the controller, check for a value in the request headers, and do something if the value isn't present (such as presenting a 404). What's the ideal way to do this? Keep in mind this is not a Web API application, just a simple web application.
Depending on what specifically you want to do, you could use a default controller which all other controllers extend. That way you can override OnActionExecuting or Initialize and do your check there.
public class ApplicationController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
//do your stuff here
}
}
public class YourController : ApplicationController
{
}
You're looking for global action filters.
Create a class that inherits ActionFilterAttribute, override OnActionExecuting() to perform your processing, and add an instances to global filter collection in Global.asax.cs (inside RegisterGlobalFilters())
Ok, so I have an existing application to which I have added a custom HttpModule. I'm registering two events in the Init() method (PreRequestHandlerExecute and PostRequestHandlerExecute). The HttpModule gets called for every 'normal' request. But not I have created an .aspx containing a few WebMethods that are being called for ajaxifying some UI components. The WebMethod gets called nicely, but the trouble is that my HttpModule does NOT get called at all (no events, no init, even no constructor) when accessing the WebMethod. The module gets called nicely when accessing the .aspx in question as a 'normal' request. But it refuses to be called when calling the WebMethod.
My .aspx looks like this:
public partial class SelectionListService : System.Web.UI.Page
{
[WebMethod]
[ScriptMethod]
public static RadComboBoxData GetItemsAsRadComboBoxData(RadComboBoxContext context)
{
...
}
}
My HttpModule look like this:
public class MyModule : IHttpModule, IRequiresSessionState
{
public MyModule ()
{
}
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(Application_PreRequestHandlerExecute);
context.PostRequestHandlerExecute += new EventHandler(Application_PostRequestHandlerExecute);
}
private void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
...
}
private void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
...
}
}
I have been digging into this for quite some time now, but I just can't get it to work. Any ideas?
PS1: the BeginRequest, etc in global.asax.cs do get called when accessing the WebMethod.
PS2: I'm running IIS7 on Windows7.
since PageMethods must be static, an instance of the Page class with all it's events and the ASP.NET pipeline never happens. You simply get the result of your PageMethod call, and that is all.
I have a project that had the same problem. We found that the first event in the pipeline that we could get to fire for the WebMethods was the AcquireRequestState event. We hooked into that with our HttpModule in order to do the authorization checking required for the application.
I don't know what your pre and post request handlers do, but maybe you could shift some of the logic into the AcquireRequestState event handler.
My project has no "global.asax" for various reasons and I can't change that (it's a component). Also, I have no access to web.config, so an httpModule is also not an option.
Is there a way to handle application-wide events, like "BeginRequest" in this case?
I tried this and it didn't work, can someone explain why? Seems like a bug:
HttpContext.Current.ApplicationInstance.BeginRequest += MyStaticMethod;
No, this is not a bug. Event handlers can only be bound to HttpApplication events during IHttpModule initialization and you're trying to add it somewhere in the Page_Init(my assumption).
So you need to register a http module with desired event handlers dynamically. If you're under .NET 4 there is a good news for you - there is PreApplicationStartMethodAttribute attribute (a reference: Three Hidden Extensibility Gems in ASP.NET 4):
This new attribute allows you to have
code run way early in the ASP.NET
pipeline as an application starts up.
I mean way early, even before
Application_Start.
So the things left are pretty simple: you need to create your own http module with event handlers you want, module initializer and attribute to your AssemblyInfo.cs file . Here is a module example:
public class MyModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
public void Dispose()
{
}
void context_BeginRequest(object sender, EventArgs e)
{
}
}
To register module dynamically you could use DynamicModuleUtility.RegisterModule method from the Microsoft.Web.Infrastructure.dll assembly:
public class Initializer
{
public static void Initialize()
{
DynamicModuleUtility.RegisterModule(typeof(MyModule));
}
}
the only thing left is to add the necessary attribute to your AssemblyInfo.cs:
[assembly: PreApplicationStartMethod(typeof(Initializer), "Initialize")]
I'm writing an app where 3rd party vendors can write plugin DLLs and drop them into the web app's bin directory. I want the ability for these plugins to be able to register their own HttpModules if necessary.
Is there anyway that I can add or remove HttpModules from and to the pipeline at runtime without having a corresponding entry in the Web.Config, or do I have to programmatically edit the Web.Config when adding / removing modules? I know that either way is going to cause an AppDomain restart but I'd rather be able to do it in code than having to fudge the web.config to achieve the same effect.
It has to be done at just the right
time in the HttpApplication life cycle
which is when the HttpApplication
object initializes (multiple times,
once for each instance of
HttpApplication). The only method
where this works correct is
HttpApplication Init().
To hook up a module via code you can
run code like the following instead of
the HttpModule definition in
web.config:
public class Global : System.Web.HttpApplication
{
// some modules use explicit interface implementation
// by declaring this static member as the IHttpModule interface
// we work around that
public static IHttpModule Module = new xrnsToashxMappingModule();
public override void Init()
{
base.Init();
Module.Init(this);
}
}
All you do is override the HttpApplication's Init() method and
then access the static instance's Init
method. Init() of the module hooks up
the event and off you go.
Via Rick Strahl's blog
Realize this is an old question, but asp.net 4 provides some new capabilities that can help here.
Specifically, ASP.NET 4 provides a PreApplicationStartMethod capability that can be used to add HttpModules programmatically.
I just did a blog post on that at http://www.nikhilk.net/Config-Free-HttpModule-Registration.aspx.
The basic idea is you create a derived HttpApplication that provides ability to add HttpModules dynamically at startup time, and it then initializes them into the pipeline whenever each HttpApplication instance is created within the app-domain.
The dll Microsoft.Web.Infrastructure.dll has a method for this inside the class DynamicModuleUtility.
The dll is shipped with WebPages 1.0
public static class PreApplicationStartCode
{
private static bool _startWasCalled;
public static void Start()
{
if (_startWasCalled) return;
_startWasCalled = true;
DynamicModuleUtility.RegisterModule(typeof(EventTriggeringHttpModule));
}
}
This worked for me for dynamic registration.
RegisterModule(typeof(RequestLoggerModule));
public class RequestLoggerModule : IHttpModule
{ ... }
https://learn.microsoft.com/en-us/dotnet/api/system.web.httpapplication.registermodule?view=netframework-4.7.2
In new versions of ASP MVC you can use Package Manager to add a reference to WebActivatorX and then do something like this
using WhateverNameSpacesYouNeed;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(YourApp.SomeNameSpace.YourClass), "Initialize")]
namespace YourApp.SomeNameSpace
{
public static void Initialize()
{
DynamicModuleUtility.RegisterModule( ... the type that implements IHttpModule ... );
}
}