【发布时间】:2021-12-03 09:04:41
【问题描述】:
我有以下逻辑来返回 wwwroot 文件夹中的图像存储。每次 Url.Action 调用控制器中的 Action 方法时,如果存在则返回用户图像,否则返回空白图像。如何将物理图像路径结果从控制器返回到 Url.Action?任何帮助将非常感激。用什么方法返回图片的物理路径?
这是我在 Navbar Razor 页面 (CSHTML) 上的用户图像代码:
<img class="rounded-circle me-1" src="@Url.Action("MyProfilePic", "MyProfile")" height="24" asp-append-version="true"/>
控制器动作方法:(.NET Core)
public async Task<IActionResult> MyProfilePic()
{
var user = await userManager.GetUserAsync(User);
var profilPicName = user.ProfilePicName;
if (profilPicName != null)
{
var ext = ".jpg";
string fullname = Path.Combine(profilPicName,ext) ;
string profilePicPath = Path.Combine(webHostEnvironment.WebRootPath, "images", fullname);
return profilePicPath //Full path of image
}
return //Path of the ImagePlaceholder
}
【问题讨论】:
-
如果您可以确定图像存在,那么一个简单的
<img src="~/images/@Model.UserProfileImage">- 如果您需要先检查它是否存在,那么可能最简单的方法是在操作中检查文件系统并更改Model.UserProfileImage 到“default.jpg”。或者,将您的图像指向一个动作并让该动作确定要使用的图像 - 这会更快,因为它将磁盘访问移出主动作,例如:<img src='@Url.Action("GetUserProfileImage")'>返回路径,但需要两次点击,所以你可以返回一个data:对象。 -
嗨@freedomn-m 感谢您的回复。问题是我的导航栏位于 _layout 共享视图中,我无法将其绑定到模型。然后我可以使用 /@Model.UserProfileImage,但这是不可能的。您建议的第二个选项似乎是一个可行的解决方案。如果您能详细说明如何使用 url.Action 方法对我有很大帮助。
-
如何知道用户在布局中是谁?像
<img src="~/images/@User.Identify.GetUser()">这样的东西然后按 id 存储你的图像。 -
return image data from an action 已经有很多解决方案,例如this question 或多或少地展示了如何做(返回
FileStreamResult) -
@freedomn-m 要使用 /@Url.Action 进行检索,我可以在我的控制器中有一个方法来在每次调用 Url.Action 时提供文件路径结果。此方法还将获取当前登录的用户。公共异步任务
MyProfilePic() { var user = await userManager.GetUserAsync(User); var profilePicName = user.ProfilePicName; if (profilPicName != null) { return ViewBag.ProfilePicName = profilePicName; } 返回 ViewBag.ProfilePicName; }
标签: c# asp.net-core-mvc asp.net-identity identity