在.NET Core自带的Angular模板项目中,我想要做一个简单的登录认证。
所以想填写用户名密码,使用guid作为key,存储登录信息,每次页面刷新的时候check它。
思路觉得没有问题,但是一直失效,修改前代码:
public class AuthController : Controller
{
private readonly IMemoryCache _cache;
public AuthController(IMemoryCache cache)
{
_cache = cache;
}
[HttpPost]
public IActionResult Post([FromBody]LoginModel model)
{
if (model != null && model.UserName == "xxxxx" && model.Password == "yyyyyyy")
{
var token = Guid.NewGuid();
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetPriority(CacheItemPriority.NeverRemove)
.SetSlidingExpiration(TimeSpan.FromDays());
_cache.Set(token, model, cacheEntryOptions);
return Ok(new { success = true, token = token, model= _cache.Get<LoginModel>(token) });
}
return Ok(new { success = false, error = "UserName or Password error." });
}
[HttpGet("check/{token}")]
public IActionResult Check(string token)
{
var model = _cache.Get<LoginModel>(token);
if (model != null && model.UserName == "xxxxx" && model.Password == "yyyyyyy")
{
return Ok(new { success = true, model });
}
return Ok(new { success = false, model });
} public class LoginModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
}
但是在调用check的api时,就是找不到。
后来发现在set的地方,guid没有ToString,所以导致两次使用过的key不一样。
修改后:
[Route("api/auth")]
public class AuthController : Controller
{
private readonly IMemoryCache _cache;
public AuthController(IMemoryCache cache)
{
_cache = cache;
}
[HttpPost]
public IActionResult Post([FromBody]LoginModel model)
{
if (!model.IsValidUserInfo())
return Ok(new { success = false, error = "UserName or Password error." });
var token = Guid.NewGuid().ToString();
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetPriority(CacheItemPriority.NeverRemove)
.SetSlidingExpiration(TimeSpan.FromDays());
_cache.Set(token, model, cacheEntryOptions);
return Ok(new { success = true, token = token });
}
[HttpGet("check/{token}")]
public IActionResult Check(string token)
{
var model = _cache.Get<LoginModel>(token);
return Ok(new { success = model.IsValidUserInfo() });
} public class LoginModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
} public static class extController
{
public static bool IsValidUserInfo(this AuthController.LoginModel me)
=> me != null && me.UserName == "xxxx" && me.Password == "yyyy";
}
注:多加了一个扩展方法,验证登录信息。