Eric
Eric

Reputation: 2380

How to determine if endpoint routing is enabled at runtime ASP.Net Core

I am converting some of my old ASP.Net Core applications from 2.1 to 3.1.

I know how to use options.EnableEndpointRouting = false to use the legacy IRouter logic; however, once I have set this, is there a flag built into ASP.Net that I can read to tell the current value of EnableEndpointRouting?

I currently call UseMvc from a completely different place from where I set EnableEndpointRouting with AddMvc, and I want to be able to decide whether to use UseMvc or UseEndpoints once I get there.

If you are wondering why I want this to even be switchable, it is part of a framework that I maintain, so the applications do not simply hard code these things inside Startup.

Upvotes: 0

Views: 247

Answers (1)

LazZiya
LazZiya

Reputation: 5719

Where do you want to do the value control? In general you can inject MvcOptions and get the value from it.

public class Foo
{
    private readonly IOptions<MvcOptions> _ops;

    public Foo(IOptions<MvcOptions> ops)
    {
        _ops = ops;
    }

    public bool IsEndPointRoutingEnabled => _ops.Value.EnableEndpointRouting;
}

Update

If you want to use GetService instead of injection to the constructor:

public class Foo
{
    private readonly IOptions<MvcOptions> _ops;

    public Foo(IServiceProvider provider)
    {
        _ops = provider.GetService(typeof(IOptions<MvcOptions>)) as IOptions<MvcOptions>;
    }

    public bool IsEndPointRoutingEnabled => _ops.Value.EnableEndpointRouting;
}

Notice that this is considered as anti-pattern and not recommended when using DI is applicable

Upvotes: 2

Related Questions