odata ApiController.User == NULL after upgrade to web api 5.0.0-rc1 - webforms

I'm using Windows Auth and it was working fine on this odata controller. But after I got the latest NuGet package (prerelease 5.0.0-rc1) something changed and ApiController.User is null. It's not passing the Windows Auth anymore. Any ideas? I tried adding the [Authorize] attribute but that didn't work - maybe that needs more config somewhere else.
public class ProductsController : EntitySetController<Product, int>
{
protected ProjectContextUnitOfWork UoW;
protected UserRepository UserRepo;
protected ProductRepository ProductRepo;
protected Project.Models.User CurrentUser;
// odata/Products/
public ProductsController()
{
if (!User.Identity.IsAuthenticated)
{
HttpResponseMessage msg = Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "User not authenticated.");
throw new HttpResponseException(msg);
}
ProjectUserPrincipal LoggedInUser = this.User as ProjectUserPrincipal;
// - closed in Dispose()
UoW = new ProjectContextUnitOfWork(false); //without lazy loading
UserRepo = new UserRepository(UoW);
ProductRepo = new ProductRepository(UoW);
CurrentUser = UserRepo.Get(LoggedInUser.Username, LoggedInUser.Domain);
}
protected override Product GetEntityByKey(int id)
{
var x = from b in ProductRepo.GetAvailableProductsWithNumbers(CurrentUser)
where b.Id == id
select b;
return x.FirstOrDefault();
}
...
}
Other details:
.NET 4.5
Web Forms
Also, when I reverted back to 5.0.0.beta2, without any other changes, it works again. So it's definitely a change in Microsoft.AspNet.WebApi. I'm ok with making code changes, I just need some tips. Thanks!

It's because you are using the ApiController.User in controller constructor. At that time, the property has not been initialized. You should:
Add [Authorize] attribute on your controller
Move the initialization code in Initialize method
So the code looks like:
[Authorize]
public class ProductsController : EntitySetController<Product, int>
{
protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
ProjectUserPrincipal LoggedInUser = this.User as ProjectUserPrincipal;
// - closed in Dispose()
UoW = new ProjectContextUnitOfWork(false); //without lazy loading
UserRepo = new UserRepository(UoW);
ProductRepo = new ProductRepository(UoW);
CurrentUser = UserRepo.Get(LoggedInUser.Username, LoggedInUser.Domain);
}
}

Related

Register and Resolving Dependencies on Request Based on Param (Autofac WEB API)

I have an Application with autofac dependency injection and I wanted to use a specific dll extension based on the parameter I have on the request.
Here's my global.asax where I initialize autofac.
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly());
containerBuilder.RegisterModule<ExModule>();
var container = containerBuilder.Build();
container.Resolve<IArtigoErp>();
Here's the autofac module where I load register my DLL's
public class ExModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
//Load DLL1 from folder and register it
RegistaDepedencias<IArtigoErp>(builder, "DLL1");
//Load DLL2 from folder and register it
RegistaDepedencias<IArtigoErp>(builder, "DLL2");
}
private void RegistaDepedencias<T>(ContainerBuilder builder, string NomeDll)
{
RegisterDep<T>(GetEnumerableTypes<T>(NomeDll), builder);
}
private void RegisterDep<T>(IEnumerable<Type> types, ContainerBuilder builder)
{
foreach (var t in types)
{
builder.RegisterType(t).As<T>();
}
}
private IEnumerable<Type> GetEnumerableTypes<T>(string NomeDll)
{
return Directory.EnumerateFiles(Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Engine"))
.Where(x => x.Contains(NomeDll) && x.EndsWith(NomeDll +".dll"))
.Select(x => Assembly.LoadFrom(x))
.SelectMany(x => x.GetTypes()
.Where(t => typeof(T).IsAssignableFrom(t) && t.IsClass));
}
}
Both my DLL's have a class that extend from IArtigoErp.
So the ideia is, based on the parameter I get on my request, I want to run the method in either DLL1 or DLL2.
Example:
if(param == 1)
_artigoErp.GetLista(); // In DLL1
if(param == 2)
_artigoErp.GetLista(); // In DLL2
EDIT 1:
The parameter comes from the post method as it follows (Guid IdLoja)
public class ArtigoController : ApiController
{
private readonly IArtigoErp _artigoErp;
private readonly IArtigoLoja _artigoLoja;
public ArtigoController(IArtigoErp artigoErp, IArtigoLoja artigoLoja)
{
_artigoErp = artigoErp;
_artigoLoja = artigoLoja;
}
[Route("PostArtigos")]
public CallResponse PostArtigos([FromBody] Guid IdLoja)
{
}
}
I guess we can also process this in the begin_request method in global.asax
Thanks in advance.

How to fake an HttpContext and its HttpRequest to inject them in a service constructor

In a console application, I would like to use a service that would normally need the current http context to be passed to its constructor. I am using Ninject, and I think I can simply fake an http context and define the proper binding, but I have been struggling with this for a few hours without success.
The details:
The service is actually a mailing service that comes from an ASP.Net MVC project. I am also using Ninject for IoC. The mail service needs the current http context to be passed to its constructor. I do the binding as follows:
kernel.Bind<IMyEmailService>().To<MyEmailService>()
.WithConstructorArgument("httpContext", ninjectContext => new HttpContextWrapper(HttpContext.Current));
However, I would like now to use this mailing service in a console application that will be used to run automated tasks at night. In order to do this, I think I can simply fake an http context, but I have been struggling for a few hours with this.
All the mailing service needs from the context are these two properties:
httpContext.Request.UserHostAddress
httpContext.Request.RawUrl
I thought I could do something like this, but:
Define my own fake request class:
public class AutomatedTaskHttpRequest : SimpleWorkerRequest
{
public string UserHostAddress;
public string RawUrl;
public AutomatedTaskHttpRequest(string appVirtualDir, string appPhysicalDir, string page, string query, TextWriter output)
: base(appVirtualDir, appPhysicalDir, page, query, output)
{
this.UserHostAddress = "127.0.0.1";
this.RawUrl = null;
}
}
Define my own context class:
public class AutomatedTasksHttpContext
{
public AutomatedTaskHttpRequest Request;
public AutomatedTasksHttpContext()
{
this.Request = new AutomatedTaskHttpRequest("", "", "", null, new StringWriter());
}
}
and bind it as follows in my console application:
kernel.Bind<IUpDirEmailService>().To<UpDirEmailService>()
.WithConstructorArgument("httpContext", ninjectContext => new AutomatedTasksHttpContext());
Unfortunately, this is not working out. I tried various variants, but none was working. Please bear with me. All that IoC stuff is quite new to me.
I'd answered recently about using a HttpContextFactory for testing, which takes a different approach equally to a console application.
public static class HttpContextFactory
{
[ThreadStatic]
private static HttpContextBase _serviceHttpContext;
public static void SetHttpContext(HttpContextBase httpContextBase)
{
_serviceHttpContext = httpContextBase;
}
public static HttpContextBase GetHttpContext()
{
if (_serviceHttpContext!= null)
{
return _serviceHttpContext;
}
if (HttpContext.Current != null)
{
return new HttpContextWrapper(HttpContext.Current);
}
return null;
}
}
then in your code to this:
var rawUrl = HttpContextFactory.GetHttpContext().Request.RawUrl;
then in your tests use the property as a seam
HttpContextFactory.SetHttpContext(HttpMocks.HttpContext());
where HttpMocks has the following and would be adjusted for your tests:
public static HttpContextBase HttpContext()
{
var context = MockRepository.GenerateMock<HttpContextBase>();
context.Stub(r => r.Request).Return(HttpRequest());
// and stub out whatever else you need to, like session etc
return context;
}
public static HttpRequestBase HttpRequest()
{
var httpRequest = MockRepository.GenerateMock<HttpRequestBase>();
httpRequest.Stub(r => r.UserHostAddress).Return("127.0.0.1");
httpRequest.Stub(r => r.RawUrl).Return(null);
return httpRequest;
}

Unable to setup MiniProfiler w/ Enity Framework 4.0 (Not code first)

I installed MiniProfiler and MiniProfiler.EF in my project via nuget.
Before using MiniProfiler I would open a connection using this in my model repository:
public class NotificationRepository
{
private CBNotificationModel.CB_NotificationEntities db;
public NotificationRepository()
{
db = new CB_NotificationEntities();
}
public NotificationContact GetNotificationContacts()
{
return db.NotificationContacts.ToList();
}
}
To use mini profiler I created:
public static class ConnectionHelper
{
public static CB_NotificationEntities GetEntityConnection()
{
var conn = new StackExchange.Profiling.Data.EFProfiledDbConnection(GetConnection(), MiniProfiler.Current);
return ObjectContextUtils.CreateObjectContext<CB_NotificationEntities>(conn); // resides in the MiniProfiler.EF nuget pack
}
public static EntityConnection GetConnection()
{
return new EntityConnection(ConfigurationManager.ConnectionStrings["CB_NotificationEntities"].ConnectionString);
}
}
The model repository now uses
db = ConnectionHelper.GetEntityConnection();
However this gives the error:
An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
Am I missing a step? I tried adding MiniProfilerEF.Initialize() and MiniProfilerEF.Initialize_EF42() in Application_start() however that just changes the errors given.
There does not seem to be much information for setting up a entity framework project to use miniprofiler unless it is codefirst.
I was able to get this working by changing my ConnectionHelper class to the following:
public static class ConnectionHelper
{
public static CB_NotificationEntities GetEntityConnection()
{
var connectionString = ConfigurationManager.ConnectionStrings["CB_NotificationEntities"].ConnectionString;
var ecsb = new EntityConnectionStringBuilder(connectionString);
var sqlConn = new SqlConnection(ecsb.ProviderConnectionString);
var pConn = new StackExchange.Profiling.Data.EFProfiledDbConnection(sqlConn, MiniProfiler.Current);
var context = ObjectContextUtils.CreateObjectContext<CB_NotificationEntities>(pConn);
return context;
}
}

Autofac, ASP.NET MVC 3 httpRequest scope and AutoMapper: No scope with a Tag matching 'httpRequest' is visible

When I use a web type registered with autofac from an automapper mapping, I get this error:
No scope with a Tag matching 'httpRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being reqested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.
When another type is resolved in the mapping it works.
When a web type is resolved from the controller it works.
Why doesnt web (or any other httprequest scoped?) types get successfully resolved in my mapping?
protected void Application_Start()
{
var builder = new ContainerBuilder();
builder.RegisterModule<AutofacWebTypesModule>();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.AssignableTo<Profile>()
.As<Profile>()
;
builder.Register(c => Mapper.Engine)
.As<IMappingEngine>();
builder.RegisterType<AnotherType>()
.As<IAnotherType>();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
var profiles = container.Resolve<IEnumerable<Profile>>();
Mapper.Initialize(c => profiles.ToList().ForEach(c.AddProfile));
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
public class HomeController : Controller
{
private readonly IMappingEngine _mapper;
private readonly Func<HttpContextBase> _httpContext;
public HomeController(IMappingEngine mapper, Func<HttpContextBase> httpContext)
{
_mapper = mapper;
_httpContext = httpContext;
}
public ActionResult Index()
{
var test = _httpContext.Invoke();
return View(_mapper.Map<Model, ViewModel>(new Model()));
}
}
public class MyProfile : Profile
{
private readonly Func<HttpContextBase> _httpContext;
private readonly Func<IAnotherType> _anotherType;
public MyProfile(Func<HttpContextBase> httpContext, Func<IAnotherType> anotherType)
{
_httpContext = httpContext;
_anotherType = anotherType;
}
protected override void Configure()
{
CreateMap<Model, ViewModel>()
.ForMember(d => d.Url, o => o.ResolveUsing(s =>
{
var test = _anotherType.Invoke().GetAValue();
return _httpContext.Invoke().Request.Url;
}))
;
}
}
public interface IAnotherType
{
string GetAValue();
}
public class AnotherType : IAnotherType
{
public string GetAValue() { return "a value"; }
}
public class ViewModel
{
public string Url { get; set; }
}
public class Model
{
}
EDIT: Its easy to create an empty MVC project, paste the code and try it out and see for yourself.
EDIT: Removed the ConstructServicesUsing call because its not required by the example. No services are resolved through AutoMapper in the example.
#rene_r above is on the right track; adapting his answer:
c.ConstructServicesUsing(t => DependencyResolver.Current.GetService(t))
Still might not compile but should get you close.
The requirement is that the call to DependencyResolver.Current is deferred until the service is requested (not kept as the value returned by Current when the mapper was initialised.)
I think you should use DependencyResolver.Current.Resolve instead of container.Resolve in
Mapper.Initialize(c =>
{
c.ConstructServicesUsing(DependencyResolver.Current);
profiles.ToList().ForEach(c.AddProfile);
});
I recently had a similar problem and it turned out to be a bad setup in my bootstrapper function. The following autofac setup did it for me.
builder.Register(c => new ConfigurationStore(new TypeMapFactory(), AutoMapper.Mappers.MapperRegistry.Mappers))
.AsImplementedInterfaces()
.SingleInstance();
builder.Register(c => Mapper.Engine)
.As<IMappingEngine>()
.SingleInstance();
builder.RegisterType<TypeMapFactory>()
.As<ITypeMapFactory>()
.SingleInstance();
I did not have to specify resolver in the Mapper.Initialize() function. Just called
Mapper.Initialize(x =>
{
x.AddProfile<DomainToDTOMappingProfile>();
});
after the bootstrapped and it works fine for me.

How to pass a mvc-mini-profiler connection to a base class from MVC3

Given this snippet of code
public abstract class Foo
{
private static SqlConnection _sqlConnection;
protected SqlConnection GetOpenConnection()
{
if (_sqlConnection == null)
{
_sqlConnection = new SqlConnection("connection string");
}
return _sqlConnection;
}
protected abstract void Execute();
}
public class FooImpl : Foo
{
protected override void Execute()
{
var myConn = GetOpenConnection();
var dog = myConn.Query<dynamic>("select 'dog' Animal");
var first = dog.First();
string animalType = first.Animal;
// more stuff here
}
}
How would you wrap the connection in a profiled connection if you don't have access to the connection creation process? Rewrite the code in the super class and wrap it there? This would involve changing hundreds of classes that inherit from the base. I'd prefer a way to change the base class, with as little changes necessary to the supers.
Thank you,
Stephen
Well after a bit of trial and error I compromised and added a ref to MvcMiniProfiler in the base library and changed the connection code a bit.
protected DbConnection GetOpenConnection()
{
if (_connection == null)
{
_connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connection string "].ConnectionString);
_connection.Open();
}
return MvcMiniProfiler.Data.ProfiledDbConnection.Get(_connection, MiniProfiler.Current);
}
private static SqlConnection _connection;
This works for both hosting in the MVC project (for profiling purposes, where we don't have that capability (QA/Prod Databases)) and WPF/Windows Service

Resources