我应该在核心 ASP.NET ClaimIdentity 中存储一个小图片头像吗? 如果没有,最好的方法是什么?



我是 ASP.NET 核心新手,我正在开发一个带有用户登录的网站(.NET core 2.1(。

我希望能够在所有使用 _Layout.cshtml 的页面中显示用户头像图像。 所以在那个文件中,对于我已经使用的用户名:@User.Identity.Name. 现在我想使用这样的东西:@User.Claims.First("avatar")

我正在使用基于 Cookie 的身份验证:

在我的"创业.cs"中:

public void ConfigureServices(IServiceCollection services) {
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// support for cookie based authentication
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => {
options.Cookie.HttpOnly = true;
options.LoginPath = "/Account/Login";
});
}

在我的"帐户控制器"中:

[HttpPost]
public async Task<IActionResult> Login(LoginModel m) {
var user = Authenticate(m.Email, m.Password); // returns null when authentication fails
if (user!=null) {
var userIdentity = new ClaimsIdentity(
new List<Claim> {
new Claim(ClaimTypes.Name, user.Company.Name),
new Claim(ClaimTypes.Email, user.Email)
}, "login");
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync(principal);
return Redirect("/"); // redirect after authentication
}
return View("Login"); // default view if cannot authenticate
}

头像图片本身将存储在Firebase数据库中,因此我需要避免对我网站的每个页面请求进行数据库查询。

由于"声明"用于授权规则,因此我认为我不应该使用它来存储可用于呈现 JPG 图片的"小"字节数组。由于我在用户会话期间在每个页面中都显示它,因此我想在登录期间将图片加载到服务器 RAM 中,并使其在用户保持登录状态时一直保留在那里。

我发现了很多例子,人们会扩展类 ClaimPrincipal 以添加新属性,但这需要一些其他代码更改(似乎与使用实体框架的 IdentityModel 相关(和 ClaimsPrincipal 对象的工厂。(如果我必须朝这个方向走,我想从我提供的代码开始一个小例子(

记住我是 ASP.NET 核心MVC的新手... 如果有人能指出我一个好的方向,我将不胜感激。

您可以添加如下自定义声明:

new Claim("Avatar", Convert.ToBase64String(byteArray));

由于它们只接受字符串,因此您应该将字节数组转换为 base64 字符串。

但是,我认为最好的方法是拥有某种存储,然后仅将图片的URL保存在数据库(和声明中(。

我不明白为什么只在用户在线时显示头像。只有用户自己才能看到他的头像吗?

但我目前正在为我的项目处理身份问题,也许这个解决方案也适合你。

我有一个用于图像底层的控制器逻辑。所有图像都在数据库中,并由特殊的媒体控制器提供。我也将它们缓存在一个文件夹中,但那是另一回事。此媒体控制器提供由其 id 标识的所有图像。路由是/media/images/{imageId:int}

这也适用于文件名而不是 id。为什么要处理与所有其他图像不同的个人资料图片?

我的标识用户类如下所示:

using System;
using Microsoft.AspNetCore.Identity;
namespace MyProject.Identity
{
public class MyProjectIdentity : IdentityUser<string>
{
//other properties...
public int ProfilePicId { get; set; }
//more other properties...
}
}

在我展示阿凡达的每个视图上,我只是这样做:

<img src="~/media/images/@User.ProfilePicId" alt="Profile Pic" />

最好将头像存储在数据库中,这样加载速度更快。

参考这个 - https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1#storage-scenarios

相关内容

最新更新