How to create a Per Request Context for my application - asp.net-core

I am playing around with the ASP.NET vNext. and I was wondering how to create my own context per request.
In older versions I would create a singleton and store it in HttpContext.Current.Items.
The idea is that I want to load some data at the beginning of the request that should be available through the entire request.

You can achieve the same with HttpContext Items. You would write a middleware like this one and you can handle your stuff inside the Invoke method.

Related

¿Is there a way to call a class method on every controller action?

I'm implementing a cache system to handle my JWT on server side to emulate a Session State , everytime an action is called i must validate the token on the server cache to see if it's still valid, is there a way to create a something like
[Authorize] or [AllowAnonymous]
To search over the request and do whatever is needed to valide it? i already have a singleton class that handles the cache system, all i need is an easy way to call the right methods.
I want to avoid calling via Dependency Injection the method on every action on every method.
I'm using Net Core 3.0, Distributed Cache, and a Web API with JWT validation.
Thank you.
You need to implement an Action Filter. See the documentation for more details

How to get a list of middlewares in ASP.NET Core

How do I get a list of active middlewares?
How do I get a list of middlewares for specific url (each url may have a different set of middlewares added to the pipeline)?
I would like to know which middlewares are being added by using some of the common builder extensions like UseMvc() or app.UseIdentity();
I know I could check the source code of each extension. Is there a runtime method to get this?
No, you can't. When you add a middleware to the pipeline, it's resolved to a Func<RequestDelegate, RequestDelegate>. The components are saved in a private field in the ApplicationBuilder implementation. You could however bake an extension method with some reflection magic to determine the actual middleware type, but it's not trivial.
You can see a list of middlewares in Stack.
You can add your middleware last, put a breakpoint somewhere in the Invoke method. When debugger will stop, you will see all previous calls to other middlewares.

Can Webapi be used in an application which is not excessed by any external application?

I'd read it somewhere that whenever one needs to do data intensive work then Webapi could be used. Ex: autocomplete textbox where we get data from using ajax on key press.
Now someone told me that Webapi shouldn't be used within applications which are not externally accessed. Rather action should be used to the same work as it is capable of returning the data back in a similar fashion to webapi.
I'd like to know your suggestions over it.
Depends on how you look at it. If all you need is ajax-ification of your controller actions, then you really don't need Web-API. Your actions can return a JsonResult and it is very easy to consume that from your client side through an AJAX call.
Web-API makes it easy for you to expose you actions to external clients. It supports HTTP protocol and Json and XML payloads automatically, out of the box, without you writing the code for it. Now, there is nothing preventing you from consuming the same Web-API actions from your own internal clients in an AJAX manner.
So the answer to your question depends on your design. If you don't have external clients, then there is no string need for you to have Web-API. Your standard controller actions can do the job.

Calling Web API action from within an actionfilter to take advantage of outputcache for repeated authorization

I wanted to take advantage of the OutputCache attribute for a authorization check to be made on an Action in a Controller. Based on a related thread and what I could tell the following design made sense, I was looking for feedback or corrections.
In other words:
1. a client calls an action on a controller which has my custom authorization filter attribute
2. The filter makes an HTTPClient call to another action on a web API controller (in the same site)
3. This action has an outputcache attribute to ensure I don't repeat an access check for the same parameters
Questions I had:
1. Is my use of OutputCache appropriate? I'm assuming a 5 minute cache lifetime.
2. In step#2 is a HttpClient call from my authorization filter the only way to make sure the pipeline for caching is built and used?
There are several related threads but I couldn't quite find one that tried to use this pattern for authorization.
FYI I did build out the solution I'd designed.
Answers for the questions I had:
Q1: OutputCache attribute on the authorization check call seems to work fine, I had to vary it using the cookie parameter, I'm a little concerned about this given cookies come from the client, but I still have the forms authorization filter higher and that should reject completely un-authenticated requests from coming in, would be happy to change to a better solution.
Q2: If i didn't make an HTTP call from my filter, the cache pipeline was not being built, so this is necessary as far as i can tell.

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