使用jwt(.Net Core WebApi)提供的值动态更改EF连接字符串

时间:2017-12-15 01:00:04

标签: c# entity-framework asp.net-web-api dependency-injection .net-core

这是我的第一个问题所以请耐心等待我!

我正在尝试创建一个多租户应用程序,其中后端根据从jwt获取的客户端ID访问不同的数据库,该客户端ID也用于授权API调用。

理想情况下,我希望能够访问Startup.cs类中的Web令牌,并使用它生成连接字符串。像这样:

public void ConfigureServices(IServiceCollection services)
{
    // Stuff

    // get jwt claims, something like: 
    // clientId = Request.Claims["ClientId"];  However Request only seems to be accessible within a controller

    // newConnectionString = logic to replace the value found in Configuration.GetConnectionString("Default") with my desired database connection string

    services.AddDbContext<KahunaDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("Default")));  // current state
        // options.UseSqlServer(newConnectionString));  // desired state
}

但是,似乎无法访问控制器外的jwt。

我想不出一种方法可以实现这一点,而不会搞砸我设置的存储库模式。

以下是我可能需要更好地了解我所处位置的其他课程。

基础存储库:

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace API.Persistence.Repositories
{
    public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class
    {
         private readonly KahunaDbContext context;
         public int ClienteId { get; set; }

         public BaseRepository(KahunaDbContext context)
         {
         }

         public void Crear(TEntity entity)
         {
              context.Set<TEntity>().Add(entity);
         }

         public async Task<List<TEntity>> GetTodos()
         {
              return await this.context.Set<TEntity>().ToListAsync();
         }

         public TEntity GetSingle(int id)
         {
             return this.context.Set<TEntity>().Find(id);
         }

         public void Borrar(TEntity entity)
         {
              this.context.Remove(entity);
         }
    }

    public interface IBaseRepository<T>
    {
        int ClienteId { get; set; }
        void Crear(T entity);
        Task<List<T>> GetTodos();
        void Borrar(T entity);
        T GetSingle(int id);
    }
}

基础控制器:

using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using APIPersistence;
using API.Persistence.Repositories;

namespace API.Controllers
{
    public class BaseController<TEntity, TEntityResource> : Controller
    {
        private readonly IMapper mapper;
        private readonly IUnitOfWork unitOfWork;
        private readonly IBaseRepository<TEntity> repository;

        public BaseController(IBaseRepository<TEntity> repository, IUnitOfWork unitOfWork, IMapper mapper)
        {
        }

        [HttpGet]
        [Authorize]
        virtual public async Task<IActionResult> Get()
        {
             List<TEntity> TEntitys = await this.repository.GetTodos();
             // List<TEntityResource> TEntityResource = this.mapper.Map<List<TEntity>, List<TEntityResource>>(TEntitys);
            return Ok(TEntitys);
        }

        [HttpPost]
        public async Task<IActionResult> Post([FromBody] TEntityResource TEntityResource)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            TEntity tEntity = this.mapper.Map<TEntityResource, TEntity>(TEntityResource);

            this.repository.Crear(tEntity);

            await this.unitOfWork.CompleteAsync();

            return Ok(tEntity);
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
             if (!ModelState.IsValid)
                 return BadRequest(ModelState);

             TEntity TEntity = this.repository.GetSingle(id);
             this.repository.Borrar(TEntity);
             await this.unitOfWork.CompleteAsync();

             return Ok(true);
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> Put(int id, [FromBody] TEntityResource TEntityResource)
        {
             if (!ModelState.IsValid)
                 return BadRequest(ModelState);

             TEntity TEntity = this.repository.GetSingle(id);
             this.mapper.Map<TEntityResource, TEntity>(TEntityResource, TEntity);

             await this.unitOfWork.CompleteAsync();

             return Ok(true);
        }
    }
}

即使您没有时间详细回答这个问题,任何指导都会非常有帮助。如果您需要任何其他信息,请与我们联系。

干杯!

0 个答案:

没有答案