Injection of Request Scope objects into MVC ActionFilterAttribute - ninject

I have a shopping cart service IShoppingCartService that is defined with Ninject as being InRequestScope
this.Bind<IShoppingCartService>().To<ShoppingCartService>().InRequestScope();
It loads the user's shopping cart and caches it internally. Once the request is over then the service object goes away.
I needed to access the shopping cart within an ActionFilter so I used the [Inject] attribute.
public class MyActionFilterAttribute : ActionFilterAttribute
{
[Inject]
public IShoppingCartService ShoppingCartService
{
get; set;
}
}
I can then use it in the action filter like this
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var cart = ShoppingCartService.ShoppingCart;
...
}
Now for the weird part. This has been working just fine for a year or more - and then suddenly (after recently upgrading Ninject and MVC) I notice that the shopping cart is being cached (i.e. not InRequestScope).
On further research I see that ActionFilters are singletons (I verified this given that the constructor was only ever called once). So once an instance of the shopping cart is loaded it is locked in forever.
So my question is - how on earth did this ever work? Did something recently change in Ninject or MVC that could have allowed this to work before.
My fix right now is to do the following :
public IShoppingCartService ShoppingCartService
{
get
{
var scs = (IShoppingCartService) DependencyResolver.Current.GetService(typeof(IShoppingCartService));
return scs;
}
}
I'm really confused though as to how this ever could have worked - and it definitely did. What should I have done instead?

Maybe while the filter attribute was only instantiated once, the property was [Injected]-ed every time the page as hit. But let's look forward :)
In 2010 a "new" way was implemented in Ninject.MVCx (x =3, 5,..) on how to inject stuff into action filters. It doesn't need to rely on attributes and it supports constructor injection. Here's how it looks like:
(Fair warning: i don't usually do asp.net development and i didn't get to try out if the following does change anything about the lifecycle of the IActionFilter, so you'll have to try it out yourself. If you do, please provide feedback)
public class MyActionFilter : IActionFilter
{
private readonly IShoppingCartService shoppingCartService;
public MyActionFilter(IShoppingCartService shoppingCartService)
{
this.shoppingCartService = shoppingCartService;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var cart = ShoppingCartService.ShoppingCart;
...
}
}
The filter then needs to be bound by a special method BindFilter:
this.BindFilter<MyActionFilter>(FilterScope.Action, 0)
.WhenControllerTypeIs<YourController>();
which would apply it to all the actions of YourController.
There's also other targets you can apply the filter to, by using:
// Is applied to all actions of controllers which have the FooAttribute
this.BindFilter<MyActionFilter>(FilterScope.Action, 0)
.WhenControllerHas<FooAttribute>();
// Is applied to all actions which have the FooAttribute
this.BindFilter<MyActionFilter>(FilterScope.Action, 0)
.WhenActionHas<FooAttribute>();
// Is applied to all actions named Index
this.BindFilter<MyActionFilter>(FilterScope.Action, 0)
.When((controllerContext, actionDescriptor) =>
actionDescriptor.ActionName == "Index");
There's some more info on that which can be found in a great article by Remo Gloor: Official Ninject MVC extension gets support for MVC3 (chapter Dependency Injection for filters)

Related

How to access Request.Properties outside of Web API Controller

I'm setting a Property on Request.Properties inside a DelegatingHandler after I pluck some data out of a header on an incoming request to a Web API.
This all works fine. I can also access Request.Properties from within the controller as well as in my Action and Exception filters. However, I also need to access this data from outside of the controller (I call a business layer class from the controller). It is data I want to include in some logs in other places,
I can see HttpContext.Current from this class, and I can see the original header from here, so I guess I could pluck it out again, but since I have already done this and put it in the Properties it seems to make more sense to get it from there. However, I don't seem to have access to the Request.Properties from anywhere else.
If this isn't the right way to do this, how else would I pass around this per-request data so that it was accessible from anywhere on the stack in Web API?
I also need to access [Request.Properties] data from outside of the controller (I call a business layer class from the controller). It is data I want to include in some logs in other places... However, I don't seem to have access to the Request.Properties from anywhere else. If this isn't the right way to do this, how else would I pass around this per-request data so that it was accessible from anywhere on the stack in Web API?
You can get it from HttpContext.Current, though it is less than ideal. Keep in mind that if any other non-web applications consume the same business layer, then HttpContext.Current would be null. HttpContext.Current is only non-null when you are running in IIS, and an IIS thread is handling the execution of the request stack. If you ever plan to self-host the web api using OWIN without IIS, there will be no HttpContext.Current.
Personally, if the data really is important enough to be passed into the business layer to be logged, then I would just pass it to the business layer method:
public Task<HttpResponseMessage> SomeAction(SomeModel model) {
... other code
someBusinessLayerObject.SomeMethod(arg1, arg2, Request.Properties["myHeaderKey"]);
}
...If you need other values from Request.Properties, then you can just pass the whole dictionary to the methods that will end up using its values.
A third option if you are using an inversion of control container would be to add some kind of scoped object dependency class and put the data in there. Then constructor inject it into your business layer class:
public interface IHaveRequestData {
IDictionary<string, object> Properties { get; set; }
}
public class RequestData : IHaveRequestData {
public IDictionary<string, object> Properties { get; set; }
}
// ioc registration pseudocode
iocContainer.Register<IHaveRequestData, RequestData>(Lifetime
.WhateverYouNeedSoThatOneOfTheseGetsCreatedForEachWebRequest);
public class SomeController : ApiController {
private readonly IHaveRequestData RequestData;
public SomeController(IHaveRequestData requestData) {
RequestData = requestData;
}
public Task<HttpResponseMessage> SomeAction() {
// you may even be able to do this part in an action filter
RequestData.Properties = Request.Properties;
}
}
public class SomeBusinessLayerComponent {
private readonly IHaveRequestData RequestData;
private readonly ILog Log;
public SomeBusinessLayerComponent(IHaveRequestData requestData, ILog log) {
RequestData = requestData;
Log = log;
}
public Task SomeMethod() {
Log.Info(RequestData["myHeader"]);
}
}

Preventing AllowAnonymous

I have a base controller which is globally marked as [Authorize]. Is there a way to prevent Controllers which inherit it from overriding the authorization requirement by simply adding the [AllowAnonymous] attribute?
Here is my exact scenario: I have three base controllers: one is for anonymous users, and two are for logged in users, both of which are globally decorated with [Authorize]. Each new controller that is created inherits from one of the base three, depending on which functionality is needed. One of the [Authorize] controllers contains "highly secure" functionality which absolutely should not be run by anonymous users. A developer inheriting from this "secure" base controller accidentally decorated some methods with [AllowAnonymous] which enabled anonymous users to potentially access the "secure" functionality in the base controller. It was caught in testing but I thought it would be a good idea to prevent that type of mistake, and I'm wondering if there is a simple way to do that. For now, I have taken all of the code inside of the secure base controller and wrapped it in blocks of:
if (Request.IsAuthenticated)
{
// do stuff
}
else
{
// redirect to login page, basically simulating what [Authorize] does
}
The above accomplishes what I want, however it kind of defeats the purpose of the global [Authorize] decoration in the first place. I'm envisioning something along the lines of:
[Authorize(AllowAnonymousOverride=false)] // this doesn't exist, but might be helpful
Is there a better way to accomplish this functionality?
The correct way to do this is to derive your own AuthorizeAttribute. The default AuthorizeAttribute looks like:
namespace System.Web.Mvc
{
public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
public virtual void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
{
throw new InvalidOperationException(MvcResources.AuthorizeAttribute_CannotUseWithinChildActionCache);
}
// This is the Important part..
bool flag = filterContext.ActionDescriptor
.IsDefined(typeof(AllowAnonymousAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor
.IsDefined(typeof(AllowAnonymousAttribute), true);
if (flag)
{
return;
}
if (this.AuthorizeCore(filterContext.HttpContext))
{
HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
cache.SetProxyMaxAge(new TimeSpan(0L));
cache.AddValidationCallback(
new HttpCacheValidateHandler(this.CacheValidateHandler), null);
return;
}
this.HandleUnauthorizedRequest(filterContext);
}
}
}
Derive your own:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public bool IsAllowAnonymousEnabled { get; set; }
public virtual void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
{
throw new InvalidOperationException(MvcResources.AuthorizeAttribute_CannotUseWithinChildActionCache);
}
// This is the Important part..
bool flag = IsAllowAnonymousEnabled
&& (filterContext.ActionDescriptor
.IsDefined(typeof(AllowAnonymousAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor
.IsDefined(typeof(AllowAnonymousAttribute), true));
if (flag)
{
return;
}
if (this.AuthorizeCore(filterContext.HttpContext))
{
HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
cache.SetProxyMaxAge(new TimeSpan(0L));
cache.AddValidationCallback(
new HttpCacheValidateHandler(this.CacheValidateHandler), null);
return;
}
this.HandleUnauthorizedRequest(filterContext);
}
}
Usage:
[CustomAuthorizeAttribute(IsAllowAnonymousEnabled = false)]
public class MyController : Controller
{
[AllowAnonymous]
public ActionResult Index()
{
// This will still execute Authorization regardless of [AllowAnonymous]
return View();
}
}
You can't call base.OnAuthorization() because it will Allow AllowAnonymous.
First, you seem to have a controller with some methods and then your approach is to inherit it so that the same methods are exposed. I wonder what's the point of having two or more controllers that expose the same data. Was is the mistake of that developer or rather it is a custom routine in your approach?
Then, you expect to have an attribute that prevents other attributes but this is clearly not possible in the language nor in the mvc framework.
Third, someone wrote a controller without unit tests or maybe with tests but no one verified these tests so that the issue was caught during manual testing phase. This indicates that the issue is wider and not only restricted to inheritance - suppose your developer wrote a controller that doesn't inherit anything and still exposes some critical data because of allow anonymous mark. Then what? Even if you have a remedy for your original issue, it wouldn't be able to catch the new possible issue.
My advice would be to have a custom analyzer attached to the post build event that scans all possible controllers and makes a list of all anonymous and restricted actions and compares it to a previously generated list. If there is a change, then an alert is created and someone has to resolve the issue manually, either by approving newly created actions or rejecting changes because a bug has been introduced.

How to correctly dispose objects registered with Autofac

I've implemented Unit of Work/Repository pattern, as described here, but I'm also using autofac and constructor injection, so I registered UnitOfWork and DbContext (PsyProfContext) class like this:
builder.Register(context => new PsyProfContext()).InstancePerHttpRequest();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerHttpRequest();
And everything works great!
Except for one thing: I'm also using enterprise library logging block, and I have implemented CustomTraceListener which is using Entity Framework to write log entry into the database.
My controller looks like this (it is empty because at the moment I just tried to verify if all the things (IoC, logging, entity framework) are working):
public class HomeController : Controller
{
private readonly UnitOfWork unitOfWork;
public HomeController(IUnitOfWork unitOfWork)
{
this.unitOfWork = (UnitOfWork) unitOfWork;
}
//
// GET: /Home/
public ActionResult Index()
{
throw new HttpException();
return View();
}
protected override void Dispose(bool disposing)
{
unitOfWork.Dispose();
base.Dispose(disposing);
}
}
And in the Write method of the CustomTraceListener class, I've tried to Resolve UnitOfWork:
DependencyResolver.Current.GetService<IUnitOfWork>() as UnitOfWork;
But I get an instance which is already disposed! so I've put some breakpoints and found out that Dispose method of the controller is called before the Write method of the CustomTraceListener class, so in the end I didn't found other solution than using DbContext (PsyProfContext) directly:
public override void Write(object o)
{
using (var conext = new PsyProfContext())
{
var customLogEntry = o as CustomLogEntry;
if (customLogEntry != null)
{
var logEntry = new LogEntry
{
//a bunch of properties
};
conext.Exceptions.Add(logEntry);
conext.SaveChanges();
}
}
}
But I don't like this solution! What's the point to use UnitOfWork and Repository pattern if you access DbContext object directly. Or what's the point in using DI in project if you create a registered object manually in some cases.
So I wanted to hear your opinion, about how to deal with this kind of situations? Is my current implementation fine, or it is definitely wrong and I should think about another one.
Any help will be greatly appreciated and any ideas are welcome!
It looks like you may have a couple of problems.
First, if you're manually disposing the unit of work object in your controller, your controller should take an Owned<IUnitOfWork> in the constructor. When the request lifetime is disposed it will automatically dispose of any IDisposable components - including the controller and any resolved dependencies - unless you specify somehow that you're going to take over ownership of the lifetime. You can do that by using Owned<T>.
public class HomeController : Controller
{
Owned<IUnitOfWork> _uow;
public HomeController(Owned<IUnitOfWork> uow)
{
this._uow = uow;
}
protected override void Dispose(bool disposing)
{
if(disposing)
{
this._uow.Dispose();
}
base.Dispose(disposing);
}
}
(Note a minor logic fix in the Dispose override there - you need to check the value of disposing so you don't double-dispose your unit of work.)
Alternatively, you could register your units of work as ExternallyOwned, like
builder
.RegisterType<UnitOfWork>()
.As<IUnitOfWork>()
.ExternallyOwned()
.InstancePerHttpRequest();
ExternallyOwned also tells Autofac that you'll take control of disposal. In that case, your controller will look like it does already. (Generally I like to just let Autofac do the work, though, and not take ownership if I can avoid it.)
In fact, looking at the way things are set up, you might be able to avoid the disposal problem altogether if you let Autofac do the disposal for you - the call to DependencyResolver would return the unit of work that isn't disposed yet and it'd be OK.
If that doesn't fix it... you may want to add some detail to your question. I see where your controller is using the unit of work class, but I don't see where it logs anything, nor do I see anything in the listener implementation that's using the unit of work.
(Also, as noted in the first comment on your question, in the constructor of your controller you shouldn't be casting your service from IUnitOfWork to UnitOfWork - that's breaking the abstraction that the interface was offering in the first place.)

How do access the HttpServerUtility in a WebAPI controller (MVC 4)

I need to access the Server.MapPath(virtualPath) method in a controller in an MVC 4 ApiController.
The answer is usually to access it from ControllerContext.HttpContext.Server. However, unlike MvcControllers, the ControlerContext for an ApiController has no HttpContext.
The WebApiAppication that is instantiated in Global.asax.cs has an HttpContext element (Context). However, unlike MVC 3 and earlier, I can't find a way to access the WebApiApplication from a controller. (Earlier generations stored a reference to it in a static Instance variable. MVC 4 removes that.)
Also, I'm trying to find something that will also work without a ton of extra scaffolding when I call the controller methods from a unit Test. I think I could access it, even in a WebApi Controller, using HttpContext.Current (at least it compiles), but I can't mock that for testing. (I'm talking unit testing here, where you call directly to the Controller methods. I've seen some recent tutorials where you unit test with a thin HttpClient, and thus test the whole stack. That seems more like low-level integration testing to me.)
This doesn't seem like it should be that difficult, but I've spent several hours googling it and trying things, and my head's getting bloody from beating it against the wall.
I'd recommend you abstracting this functionality:
public interface IMyDependency
{
string MapPath(string path);
}
and then have an implementation:
public class MyConcreteDependency: IMyDependency
{
public string MapPath(string path)
{
return HostingEnvironment.MapPath(path);
}
}
and finally your ApiController is completely independent on all static method calls making it unit test friendly:
public class MyController: ApiController
{
private readonly IMyDependency dependency;
public MyController(IMyDependency dependency)
{
this.dependency = dependency;
}
public HttpResponseMessage Get()
{
var path = this.dependency.MapPath("~/App_Data");
...
}
}
For ApiControllers, build yourself a DelegatingHandler and push all of your goodies onto request.Properties. You can then retrieve them from your request whether you are testing or running live. The benefit is that you then have zero dependency on Session in your Controller.
MessageHandler
public class ContextHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
// get the goodies to add onto the request
var goodies = /* call to goodieGoodieYumYum */
// add our goodies onto the request
request.Properties.Add(Constants.RequestKey_Goodies, goodies);
// pass along to the next handler
return base.SendAsync(request, cancellationToken);
}
}
Controller Action
var goodies = (List<Goodie>)Request.Properties[Constants.RequestKey_Goodies];

MVC 4 How to process a url parameter on every page, base controller?

Looking for some guidance in designing my new MVC 4 app.
I would like to have a url parameter s=2011 on every page of the app to let me know what year of data I'm working with. Obviously, the user will have a way to change that parameter as needed.
I will need that parameter in every controller and wondering the best way to do this. I was thinking of creating a base controller that reads Request.QueryString and puts the year into a public property. However, considering all the extensability points in MVC, I'm wondering if there's a better way to do this?
This very much depends on the design of your app, but just to give you two alternatives
IActionFilter
If you are doing data context per request you can use a global IActionFilter to hook pre-action execution globally and apply a query filter to your data context behind the scenes.
Major down-side of this is that to test the controller you will need to have the full MVC pipeline setup so that the actionfilter gets applied properly.
Dependency Injection
Instead of using sub-classing (base controller as you say) you can use dependency injection . Keeping things more loose will allow you to pull the filter from query string, cookie, user setting in the database or whatever else - without your controller knowing where it comes from.
Here is some pseudo code how I would do it if I was using something like Entity Framework or Nhibernate (also I am sure applicable with other technologies as well)
public Car
{
public string Year { get; set; }
}
public class CarsDataContext : DbContext
{
private IQuerable<Cars> _cars = null;
private Func<Car, bool> _carsFilter = null;
public IQuerable<Car> Cars {
get {
if (_carsFitler != null)
return _cars.Where(_carsFitler);
return _cars;
}
set { _cars = value; }
}
public void ApplyCarsFilter(Func<Car, bool> predicate)
{
_carsFilter = predicate;
}
}
Assuming you have dependency injection setup already (NInject or whichever other framework) in you can configure how the context to be intialized
Bind<CarsDataContext>().ToMethod(() => {
string yearFilter = GetYearFilter(); // can be coming from anywhere
CarsDataContext dataContext = new CarsDataContext();
dataContext.Applyfilter(car => car.Year == yearFilter);
return dataContext;
}).InRequestScope();
Then my controller knows nothing about the data filtering and I can easily test it:
class MyController : Controller
{
public MyController(CarsDataContext dataContext)
{
}
...
}
However I would only do this is filtering the dataset was across many controllers and important part of my software. Otherwise it's pure over-engineering.