实体框架缓存结果

时间:2018-05-22 12:38:51

标签: c# entity-framework asp.net-web-api oauth unity-container

我遇到了Entity框架缓存数据的问题。即我有一个管理面板,你可以在其中更改用户角色和其他用户数据,问题是我的服务返回用户的旧数据。为了变得更加棘手,它只会在登录时发生。我怀疑它必须做一些实例化DBContext和Unity DI。

以下是我的类:Startup.cs

<Window x:Class="WpfApplication5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication5"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style x:Key="MouseOverHighlightStyle" TargetType="Rectangle">
            <Setter Property="Fill" Value="Red" />
            <Setter Property="Opacity" Value="0" />
            <Setter Property="Grid.Column" Value="0" />
            <Setter Property="Grid.ColumnSpan" Value="4" />
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Opacity" Value="0.3" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid ShowGridLines="True">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Rectangle Grid.Row="0" Style="{StaticResource MouseOverHighlightStyle}" />
        <Rectangle Grid.Row="1" Style="{StaticResource MouseOverHighlightStyle}" />
        <Rectangle Grid.Row="2" Style="{StaticResource MouseOverHighlightStyle}" />
        <Rectangle Grid.Row="3" Style="{StaticResource MouseOverHighlightStyle}" />
    </Grid>
</Window>

ApplicationOAuthProvider.cs

public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the application for OAuth based flow

        PublicClientId = "self";
        var container = GlobalConfiguration.Configuration.DependencyResolver;

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/api/users/token"),
            Provider = new ApplicationOAuthProvider(PublicClientId,(IMembershipService)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IMembershipService))),
            AuthorizeEndpointPath = new PathString("/api/users/login"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
            // In production mode set AllowInsecureHttp = false
            AllowInsecureHttp = true
        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);
    }
public static void Register(HttpConfiguration config)
    {

        // security
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
        // routes
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var container = new UnityContainer();

        container.RegisterType<TagModel>(new HierarchicalLifetimeManager());
        container.RegisterType<IRoleRepo, RoleRepo>(new TransientLifetimeManager());
        container.RegisterType<IUserRepo, UserRepo>(new TransientLifetimeManager());
        container.RegisterType<IMembershipService, MembershipService>(new TransientLifetimeManager());
        container.RegisterType<IEncryptionService, EncryptionService>(new TransientLifetimeManager());


        IoC = container;

        // SignalR dependency injection
        config.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
        var unityHubActivator = new UnityHubActivator(container);
        GlobalHost.DependencyResolver.Register(typeof(IHubActivator), () => unityHubActivator);

        // For more information, refer to: http://www.asp.net/web-api
        config.EnableSystemDiagnosticsTracing();
        config.EnsureInitialized();
    }

UserRepository.cs:EntityBaseRepo

public ApplicationOAuthProvider(string publicClientId,IMembershipService membershipService)
    {
        if (publicClientId == null)
        {
            throw new ArgumentNullException("publicClientId");
        }
        _publicClientId = publicClientId;
        this.membershipService = membershipService;
    }
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        User user = membershipService.ValidateUser(context.UserName, context.Password);
        if (user == null) 
        {
            context.SetError("invalid_grant", "Korisničko ime ili lozinka nisu ispravni.");
            return;
        }

        ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
        foreach (var role in user.roles)
        {
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, role.role_name));
        }
        oAuthIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.username));


        ClaimsIdentity cookiesIdentity = new ClaimsIdentity(context.Options.AuthenticationType);

        AuthenticationProperties properties = CreateProperties(context.UserName,
            Newtonsoft.Json.JsonConvert.SerializeObject(user.roles.Select(x => x.role_name)), user.Location.Naziv);
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        ticket.Properties.AllowRefresh = true;

        ticket.Properties.ExpiresUtc = DateTimeOffset.Now.AddMinutes(30);
        context.Validated(ticket);
        context.Request.Context.Authentication.SignIn(cookiesIdentity);
    }

EntityBaseRepo.cs

public User GetSingleByUsername(string username)
    {
        return this.GetSingle(x => x.username == username, u => u.Location);
    }

UserController.cs

public T GetSingle(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> query = _context.Set<T>();
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }

        return query.Where(predicate).SingleOrDefault();
    }

请注意,当我更改用户的角色或其他属性并经历登录过程时,我会获得旧数据,但是当我向UserController发送请求时,即使我使用相同的服务来检索它,我也会获得新数据。有人能解释为什么会发生这种情况并提出一些解决方案吗?感谢

编辑 TagModel.cs(DBContext)

public UserController(IMembershipService membershipService, IUserRepo userRepo,
            ILocationRepo locationRepo, IRoleRepo roleRepo) {
            this.membershipService = membershipService;
            this.userRepo = userRepo;
            this.roleRepo = roleRepo;
            this.locationRepo = locationRepo;
        }

        public IHttpActionResult GetByUsername(string username, string password)
        {
            User user = membershipService.ValidateUser(username, password);
            if (user == null) {
                return BadRequest("Korisnik ne postoji.");
            }
            UserViewAdmin userView = AutoMapper.Mapper.Map<UserViewAdmin>(user);
            return Ok(user);
        }

0 个答案:

没有答案