How do you access HttpContext.Items from ApiController - asp.net-mvc-4

Is HttpContext.Items still considered a reasonable place to share things between different parts of a request? Particularly HttpHandler's outside of MVC, like WIF extensibility points.
How do you access this dictionary from within MVC4's ApiController? Without using HttpContext.Current static methods (I still want it unit testable). The normal controller had HttpContextBase/Wrapper which abstracted it a bit for testing.

Use Request.Properties inside the Web API Controller.
When implementing an ActionFilterAttribute it's filterContext.Request.Properties

Related

Using global state in ASP.Net Core

In my current Asp.Net application I am finding a number core services that are slowly spreading throughout the application through the use of Dependency Injection. One of those services is the need to know who the current authenticated user is. I have a UserService that encapsulates the logic for getting the CurrentUser, but it seems like I am injecting this same service almost everywhere in my application. Is there a different method I could be using for accessing this Global service without constantly growing my constructors to inject yet another object into my classes? (of course I still want to maintain testability)

Unit test to ensure all required services are added to the .Net Core DI container

My team maintains a very large .Net Core 2.1 web site. Lots of controllers, lots of services that get injected into the controllers via constructor injection.
Sometimes due to developer error a service class is no longer added to the DI container during startup. Obviously this leads to an exception when MVC tries to construct a controller that relies on that service (in response to an incoming request).
Problem is that this may affect only some lightly used controller, so our (far from perfect) regression testing doesn't pick up the regression bug. But it is still bound to be picked up by one of our (very demanding) customers.
I though of writing a unit test that would
Instantiate a ServiceCollection class (that implements IServiceCollection);
Call our own method that adds all services to that service collection (the same method used during normal startup);
Find all controllers through reflection, and try to construct them the same way MVC does - by getting dependent services from the DI container.
So my question is:
Does this approach make sense?
Is there an example somewhere that I could use?
Failing an example, how would I achieve 1) and 3) ?

WebAPI endpoints without controllers

Is it possible to call WebAPI endpoints without extending the Controller base class? I have a background service (base class HostedService implementing IHostedService) in .Net Core. My class structure is already set in stone so I can't change the base class of my background services. But it would be a huge help if I could call url endpoints on them without actually having a separate controller.
Is this possible?
EDIT: My background services look exactly like this.
Why don't you use something similar to ValuesController in the link you provided?
You only have to create a new Controller with almost any logic, just calls to your Hosted service.

Accessing HTTP Headers in ASP.Net Core Business Logic

I am using ASP.Net core and I have a requirement to access a specific HTTP Header in a business logic class (not a controller or action).
To provide a full picture of the configuration here, I have a custom ASP.Net Core Middleware which based on some logic will add a value into a custom HTTP Header, it is the value from this header that I need to access in the business logic class.
Currently the way that I achieve this is to inject an HttpContextAccessor, using the following DI registration.
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
In the class which requires access to the HTTP Headers I then request an IHttpContextAccessor using constructor injection and use this to access the relevant HTTP Header.
Doing the above works fine and gives me the results that I require, looking around various articles on the Internet however the general consensus appears to be to avoid using HttpContext.Current in ASP.Net Core.
If the above is the case, is there a better way for my business logic class to access the value that my custom middleware is inserting into a custom HTTP Header?
I should be clear, whilst at present the middleware is storing the required value in a HTTP Header for use by the business logic class, I am open to other methods of the middleware making the required value available to the business logic class if there is a better approach.
Any questions or clarifications, please let me know.
There is no HttpContext.Current in ASP.Net Core, so it's easy to avoid using it. You would have to implement your own extension method if you wanted it, but the general feeling in the .Net Core community is that it's much better to use IHttpContextAccessor.
In earlier versions of .Net Core an implementation of IHttpContextAccessor was auto registered in the DI container. In more current version you have to register it yourself with the line of code you mentioned:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Injecting IHttpContext into your method that needs access to the headers is a workable approach. Or if you like you could use a helper method that places a copy of the headers in a simpler structure and then pass that object in to your class since it doesn't really need access to the full HttpContext.

MVC4, UnitOfWork + DI, and SimpleAuthentication .. how to decouple?

I'm currently working on an MVC4 project, i make use if Ninject to inject a UnitOfWork into my controllers, and I'm using UnitOfWork + Generic Repository pattern.
I don't like VS2012 MVC4 template because it directly uses database access (db initialization, for example).
My project divides in:
a UI project (the mvc4 application), with Forms Authentication
a Domain project (the db entities, the repositories, the UnitOfWork interface plus two UnifOfWork implementations, one with MOQ and one with EF; they are injected into UI controllers via Ninject).
I looked at this example:
http://kevin-junghans.blogspot.it/2013/03/decoupling-simplemembership-from-your.html
related to this question
SimpleMembership - anyone made it n-tier friendly?
And now I have some question:
How can i inject my UoW here? WebSecurity class is static, there is no contructor, it directly instantiate the UoW to perform activities on db ...
I always have to initialize WebMatrix to directly access DB? This piece of code:
public static void Register()
{
Database.SetInitializer<SecurityContext>(new InitSecurityDb());
SecurityContext context = new SecurityContext();
context.Database.Initialize(true);
if (!WebMatrix.WebData.WebSecurity.Initialized)
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection("DefaultConnection",
"UserProfile", "UserId", "UserName", autoCreateTables: true);
}
breaks my decoupling with the Domain .. how can i make WebSecurity using my UnitOfWork for example? what is the best practice?
How can i store additional data (for example, EmailAddress and so on) and retrieve it, without performing a Database query everytime i have to access the User profile? Something like the old CustomPrincipal ... Custom principal in ASP.NET MVC
Thank you!
You have a lot of questions here Marco. Let me take a stab at them.
How to inject a UOW
Static classes and dependency injection do not mix well, as pointed out in this QA. When I first went through this exercise of decoupling SimpleMembership the concentration was just on decoupling from the domain, as discussed in the article you referenced. It was just a first step and it can be improved on, including making it easier for dependency injection. I debated whether to make WebSecurity static or not and went with static because that is how the original SimpleMembership is implemented, making it a more seamless transition for user of the SimpleSecurity. SimpleSecurity is an open source project and contributions are welcome. Making it non-static would not be difficult and probably makes sense in the long run. Once it is made non-static we could use a Factory pattern to create the UnitOfWork and inject the appropriate Factory.
Why do I have to Register WebSecurity?
SimpleSecurity is just a wrapper around the WebMatrix WebSecurity classes, which require initialization. The Register method just makes sure that WebMatrix is initialized and initializes our database. I disagree that having this method call in the Globa.asax couples it with the Domain in any way. Having it work with your UnitOfWork should have nothing to do with the Application Domain, or with having to call a Register method at application start-up.
How can I store additional data (ex: email) and retrieve it, without performing a database query every time?
This is actually accomplished quite easy in .NET 4.5 by using ClaimsPrincipal. All principals in .NET 4.5 inherit from ClaimsPrincipal, which allows you to store information in the principal as claims. Claims are basically key value pairs that let you store any type of data on the user. For example in ASP.NET the roles for a user are stored as claims. To add your own claims you need to do something called claims transformation. Then to retrieve the information you can create a custom claims principal. Adding this to SimpleSecurity would be a nice feature.