简体   繁体   中英

ASP.NET 5 Access session in custom Policy

I'm trying to do a custom Policy for my BaseController. The purpose for this policy is to prevent the repetition of code in every other controller.

services.AddAuthorization(options =>
{
    options.AddPolicy("PolicyName", policy =>
    {
        policy.AddRequirements(*INSERT POLICY HERE*);
    });
});

I'm Trying to add the policy like this in the ConfigureServices method in Startup.cs

What's the catch?

I want to access the Session in my policy because I need it in my calculations. I do that using the dependency injection of IHttpContextAccessor .

The problem arises in the INSERT POLICY HERE part. Because I'm supposed (from what I saw online) to do: new MyPolicy()

But that doesn't work because it needs the IHttpContextAccessor .

How can I pass it into the policy? And if there are better ways of doing this please feel free to share

The examples you've seen online are simplified, but you don't have to have the policy and the requirements in the same class. Requirements are basically data - for example an age requirement would hold the age you wish to check. So, separate the requirement into its own class, then you can new it up without the DI problem, and policy will be newed up as required via the DI container.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM