Accessing HTTP Headers in ASP.Net Core Business Logic - asp.net-core

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.

Related

What is the difference between AddAuthentication and AddAuthenticationCore?

Looking at the code for AuthenticationServiceCollectionExtensions.AddAuthentication() vs AuthenticationCoreServiceCollectionExtensions.AddAuthenticationCore(), it looks like AddAuthentication implicitly calls AddAuthenticationCore, adds some other goodies, and then returns a new instance of AuthenticationBuilder instead of just returning IServiceCollection.
Am I understanding the code correctly? If so, are there generally any reasons to call AddAuthenticationCore instead of AddAuthentication outside of writing your own extension?
It seems to be a typical pattern in ASP.NET Core: the Add[xxx]Core methods add the bare minimum to enable a feature, but without any bells and whistles. It's also probably used to make unit testing the core features easier.
You can make a parallel with the AddMvc vs AddMvcCore methods. There's a question that asks Should I use AddMvc or AddMvcCore for ASP.NET Core MVC development?, and the gist is that it allows for fine-grained control on what middleware you want to use.
To answer your question: for a typical user, there's probably no reason to use AddAuthenticationCore.
Actually there is a reason. Currently AddAuthentication() also adds data protection services, which you may not need - for example if you are writing your own Authentication Scheme. So instead you can do this:
services.AddAuthenticationCore(o => {
o.DefaultScheme = "My Custom Scheme";
});
services.AddWebEncoders();
services.AddSingleton<ISystemClock, SystemClock>();
var authBuilder = new AuthenticationBuilder(services);
however I fully expect this to break in future versions of asp.net core as it's undocumented and a bit of a hack.

Http handler in asp.net core

Now i have asp mvc 5 .net framework project and handlers (ashx files with custom logic) to process customer needs (i.e. pricelists in custom format).
I intend to move to asp core, and the question : is there an equivalent to handler?
Articles on internet suggest to put logic to middleware, but this is inconvenient way in my case.
Can you explain what do you need that middlewares cannot provide them for you?
Middlewares are built in a way that you can completely migrate from old Http Handlers/Modules to them.
https://learn.microsoft.com/en-us/aspnet/core/migration/http-modules?view=aspnetcore-2.1
Razor pages with it's own logic and model best way to substitute custom handlers in my case
You could use Middleware or Interceptor for tracking any incoming request.
The most important difference between them is that, you could use interceptor per any action too - for this you should use dependency injection.

IAuthenticationFilter equivalent in MVC6

I'm moving a Web Api 2 project to MVC 6, since Microsoft is merging the two APIs in ASP.NET 5. In my WebApi project I had a custom Attribute Filter class that would authenticate, authorize and prevent transaction replays using a combination of public key, private key and HMAC authentication (basically, doing this with some tweaks to fit into my project).
Now in MVC6, as far as I understand I must stop using anything in the Microsoft.Web.Http namespace and instead use Microsoft.AspNet.Mvc. So I have done that, but the Microsoft.AspNet.Mvc.Filters doesn't seem to have any equivalent of Web Api 2's IAuthenticationFilter.
This is a problem for me because my customer AuthenticationFilter implemented all of IAuthenticationFilter, with all the logic in there. More importantly, it was using the Context to temporarily store the public key of the account, so my controller could access it to load up the account in turn.
So my question is, what is the proper way to filter requests in MVC6, using an Authentication Filter-like class to intercept the requests and return the appropriate status codes? I can't find any article that goes specifically in these details (they all tend to cover MVC5).
I know it's an older question, but hopefully someone (maybe even yourself) might find value in the answer.
MVC6 does in fact have an alternative. You have an
public abstract class AuthorizationFilterAttribute :
Attribute, IAsyncAuthorizationFilter, IAuthorizationFilter, IOrderedFilter
which basically tells you, that you can create your custom class, derive it from this (namespace of all of these interfaces, btw, is Microsoft.AspNet.Mvc.Filters and that should be it. You can either decorate the action with it, or you can do this in Startup.cs, to apply to all actions:
public void ConfigureServices(IServiceCollection services)
{
// Add MVC services to the services container.
services.AddMvc(options =>
{
// add an instance of the filter, like we used to do it
options.Filters.Add(new MySpecialFilter());
});
services.AddTransient<LogFilter>();
}
If you want to use a bit more logic in the filter (e.g. my LogFilter above) which is instantiated through DI, you need to use either Service Filters or Type Filters.
You can now decorate the actions with [ServiceFilter(typeof(LogFilter))] or use o.Filters.Add(new ServiceFilterAttribute(typeof(LogFilter))); in the Startup.cs file. But keep in mind, to do this you need to register the type with the DI container, like I did above with the .AddTransient<>() call.
IAuthenticationFilter is no more and IAuthorizationFilter simply does not replace it in MVC 6
Reason: authentication is NOT EQUAL to authorization.
Therefore IMO the authentication filter should stay available!

ServiceStack and NHibernate Unit Of Work Pattern

Long story as brief as possible...
I have an existing application that I'm trying to get ServiceStack into to create our new API. This app is currently an MVC3 app and uses the UnitOfWork pattern using Attribute Injection on MVC routes to create/finalize a transaction where the attribute is applied.
Trying to accomplish something similar using ServiceStack
This gist
shows the relevant ServiceStack configuration settings. What I am curious about is the global request/response filters -- these will create a new unit of work for each request and close it before sending the response to the client (there is a check in there so if an error occurs writing to the db, we return an appropriate response to the client, and not a false "success" message)
My questions are:
Is this a good idea or not, or is there a better way to do
this with ServiceStack.
In the MVC site we only create a new unit
of work on an action that will add/update/delete data - should we do
something similar here or is it fine to create a transaction only to retrieve data?
As mentioned in ServiceStack's IOC wiki the Funq IOC registers dependencies as a singleton by default. So to register it with RequestScope you need to specify it as done here:
container.RegisterAutoWiredAs<NHibernateUnitOfWork, IUnitOfWork()
.ReusedWithin(ReuseScope.Request);
Although this is not likely what you want as it registers as a singleton, i.e. the same instance returned for every request:
container.Register<ISession>((c) => {
var uow = (INHibernateUnitOfWork) c.Resolve<IUnitOfWork>();
return uow.Session;
});
You probably want to make this:
.ReusedWithin(ReuseScope.Request); //per request
.ReusedWithin(ReuseScope.None); //Executed each time its injected
Using a RequestScope also works for Global Request/Response filters which will get the same instance as used in the Service.
1) Whether you are using ServiceStack, MVC, WCF, Nancy, or any other web framework, the most common method to use is the session-per-request pattern. In web terms, this means creating a new unit of work in the beginning of the request and disposing of the unit of work at the end of the request. Almost all web frameworks have hooks for these events.
Resources:
https://stackoverflow.com/a/13206256/670028
https://stackoverflow.com/search?q=servicestack+session+per+request
2) You should always interact with NHibernate within a transaction.
Please see any of the following for an explanation of why:
http://ayende.com/blog/3775/nh-prof-alerts-use-of-implicit-transactions-is-discouraged
http://www.hibernatingrhinos.com/products/nhprof/learn/alert/DoNotUseImplicitTransactions
Note that when switching to using transactions with reads, be sure to make yourself aware of NULL behavior: http://www.zvolkov.com/clog/2009/07/09/why-nhibernate-updates-db-on-commit-of-read-only-transaction/#comments

Ninject dependency into AuthorizationAttribute MVC4 Web API RC

I have a custom authorization attribute, required only for some actions, which checks the request headers for a custom token. The token is checked in a database. Checking the database requires access to a service which I would like to have injected through the constructor.
The way I have read this can be done (here, here, and here) is by having a constructor-less filter and injecting the dependent one like this:
kernel.BindFilter<MyAuthorizeFilter>(FilterScope.Controller, 0).WhenControllerHas<MyAuthorizeAttribute>();
However the BindFilter method is not available to me as I have setup Ninject as described here. This is using Ninject.Web.Common instead of Ninject MVC3 as I read that Ninject MVC3 would not work with MVC4 RC. How else can I go about accomplishing this?
I have read also that I could add to GlobalFilters.Filters - however I don't want it to be present on every action.
Thanks in advance for any answers.
I'm not completely sure I see how you have set up your application, but my experience has been that if you want a filter for a WebApi controller you need to add it to the HttpFilterCollection that is available from the GlobalConfiguration.Filters. This is a Different set of filters than what MVC uses (through the GlobalFilterCollection).