Web API-在应用程序的整个生命周期(如会话)中保存用户数据

时间:2018-08-26 07:11:08

标签: c# session asp.net-web-api

如何在整个应用程序生命周期(如会话)中将用户数据保存在纯Web Api应用程序中,以便在每个请求上我们都可以使用保存的用户数据。 我看到在WEB API中,每个请求都是独立的,与上一个请求没有连接,因此不能使用Session。

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

您需要从Nuget安装Microsoft.Owin。然后将此内容添加到您的启动课程中。

public void ConfigureAuth(IAppBuilder app) 
        { 

            var OAuthOptions = new OAuthAuthorizationServerOptions 
            { 
                AllowInsecureHttp = true, 
                TokenEndpointPath = new PathString("/token"), 
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20), 
                Provider = new SimpleAuthorizationServerProvider() 
            }; 

            app.UseOAuthBearerTokens(OAuthOptions); 
            app.UseOAuthAuthorizationServer(OAuthOptions); 
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); 

            HttpConfiguration config = new HttpConfiguration(); 
            WebApiConfig.Register(config); 
        } 

        public void Configuration(IAppBuilder app) 
        { 
            ConfigureAuth(app); 
            GlobalConfiguration.Configure(WebApiConfig.Register); 
        }

然后需要添加

之类的提供程序
[EnableCors(origins: "*", headers: "*", methods: "*")]  
    public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider  
    {  
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)  
        {  
            context.Validated(); //   
        }  

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)  
        {  
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);  
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });  

            using (var db = new TESTEntities())  
            {  
                if (db != null)  
                {  
                    var empl = db.Employees.ToList();  
                    var user = db.Users.ToList();  
                    if (user != null)  
                    {  
                        if (!string.IsNullOrEmpty(user.Where(u => u.UserName == context.UserName && u.Password == context.Password).FirstOrDefault().Name))  
                        {  
                            identity.AddClaim(new Claim("Age", "16"));  

                            var props = new AuthenticationProperties(new Dictionary<string, string>  
                            {  
                                {  
                                    "userdisplayname", context.UserName  
                                },  
                                {  
                                     "role", "admin"  
                                }  
                             });  

                            var ticket = new AuthenticationTicket(identity, props);  
                            context.Validated(ticket);  
                        }  
                        else  
                        {  
                            context.SetError("invalid_grant", "Provided username and password is incorrect");  
                            context.Rejected();  
                        }  
                    }  
                }  
                else  
                {  
                    context.SetError("invalid_grant", "Provided username and password is incorrect");  
                    context.Rejected();  
                }  
                return;  
            }  
        }  
    }

您可以根据需要添加索偿数量。然后修改您的WebApiConfig 公共类WebApiConfig
    {
        公共静态无效寄存器(HttpConfiguration配置)
        {
            // Web API配置和服务

        EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");  
        config.EnableCors(cors);  

        // Web API routes  
        config.MapHttpAttributeRoutes();  

        config.Routes.MapHttpRoute(  
            name: "DefaultApi",  
            routeTemplate: "api/{controller}/{id}",  
            defaults: new { id = RouteParameter.Optional }  
        );  

        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();  
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();  
    }  
}

然后测试您的令牌,例如enter image description here

然后,您通过授权标头传递令牌。然后得到您的要求。

api请求enter image description here的示例

获取索赔数据的示例代码

var principal = this.Request.GetRequestContext().Principal as ClaimsPrincipal;
var claims = principal.Claims.ToList();
            var age = claims.FirstOrDefault(c => c.Type == "Age")?.Value;

答案 1 :(得分:-1)

您可以使用会话变量,例如:

Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;

要使用会话变量:

// When retrieving an object from session state, cast it to 
// the appropriate type.
ArrayList stockPicks = (ArrayList)Session["StockPicks"];

// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;

有关信息,请访问:MSDN