Asp.net core 2.0 conditional service or conditiona

2019-04-11 10:16发布

I am developing web api(s) using Asp.net core 2.0. Now the thing I need is to use different connection strings which will be specified in the headers of the user.

I have previously seen this (not directly about this question):

        app.Use(async (context, next) =>
        {
            if (string.IsNullOrWhiteSpace(context.Request.Headers["Authorization"]))
            {
                if (context.Request.QueryString.HasValue)
                {
                    var token = context.Request.QueryString.Value
                        .Split('&')
                    .SingleOrDefault(x => x.Contains("authorization"))?.Split('=')[1];

                    if (!string.IsNullOrWhiteSpace(token))
                    {
                        context.Request.Headers.Add("Authorization", new[] { $"Bearer {token}" });
                    }
                }
            }
            await next.Invoke();
        });

But how should I change the connection string in a way like this?

Am I going in the right direction?

Update

I am looking for a middle ware like this:

        app.Use(async (context, next) =>
        {
            if (!string.IsNullOrWhiteSpace(context.Request.Headers["TestMode"]) && context.Request.Headers["TestMode"] == true)
            {
                // TODO Change the connection string here
            }
            await next.Invoke();
        });

But don't know what to put in the TODO.

0条回答
登录 后发表回答