1

I have a Swagger project where I'm doing OAuth (token provider + verification). Everything is working fine, but the token provider was implemented as middleware based on a sample I found online. I want to convert the token provider middleware to a controller so it shows up in Swagger and users quit bugging me on how to get a token :).

In the startup.cs, I created a TokenProviderOptions object and populated it with values that live in the startup.cs (since they also get passed to the oauth verification part). I was then doing:

app.UseMiddleware<TokenProviderMiddleware>(Options.Create(tokenProviderOptions));

and the middleware was getting the options.

Now that I'm getting rid of the middleware, how can I pass in the tokenProvider options to the controller? Seems kind of weird to put it in DI as a singleton.

1
  • I'm curious, did you use the DarksideCookie blog to do your OAuth originally? Commented Jan 7, 2019 at 23:53

1 Answer 1

3

You can resolve options from the dependency injection container in controllers and other services using the IOptions<T> interface. For example:

public class TokenProviderController
{
    private readonly IOptions<TokenProviderOptions> _options;

    public TokenProviderController(IOptions<TokenProviderOptions> options)
    {
        _options = options;
    }
}

You can then access the options values using _options.Value.

The options can be configured in the startup class. Typically you populate them from configuration:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    private IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<TokenProviderOptions>(Configuration);
    }

    // ...
}

If your options consist of hard-coded values, you can use a delegate to configure the binding:

services.Configure<TokenProviderOptions>(o =>
{
    o.Foo = "Bar";
});

For more info check out the documentation on the options pattern.

Sign up to request clarification or add additional context in comments.

2 Comments

I got it to work by passing in (null, (x) => set options)... was that your intention? In your code sample, where would you pass in the TokenProviderOptions instance?
@SledgeHammer there are different ways to configure the options. If your configuration consists of hard-coded values you can indeed use a delegate to bind them. Please take a look at the updated answer and the documentation I linked to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.