简体   繁体   English

在mvc4中的_layout中显示数据库中的图像

[英]Display image from database in _layout in mvc4

Hi all I am having my _layout as follows which works as per my requirement, but here there are couple of things I got strucked ie I would like to display the corresponding image for that I write as follows 大家好我所有我的_layout按照我的要求按照以下方式工作,但是这里有几件事情我已经被击中了,即我想显示相应的图像我写的如下

@if (Session["UserName"] != null)
{
 <div class="logged_in" id="user_navigation" runat="server">
 <a title="Your Profile" href="">
 <img alt="" src="@Url.Action("GetPhoto", new { photoId = Session["UserName"] })" height="50" width="50" class="photo" />
</a>
</div>
}

But this is not showing image as per required for me so can some one help me I would like to display the image from the database after user logged in also I would like to display the session values in some control too 但是这并没有按照我的要求显示图像所以有人可以帮助我我想在用户登录后显示数据库中的图像我也希望在某些控件中显示session

This is my controller code 这是我的控制器代码

public ActionResult GetPhoto(string photoId)
        {
            byte[] photo = null;
            var v = db.tblUsers.Where(p => p.UserName == photoId).Select(img => img.Photo).FirstOrDefault();
            photo = v;
            return File(photo, "image/jpeg");
        }

You seem to have a problem with the <img> syntax. 您似乎遇到了<img>语法的问题。 It should be like this: 它应该是这样的:

<img alt="" src="@Url.Action("GetPhoto","User", new { photoId = Session["UserName"].ToString() })" height="50" width="50" class="photo" />

According to the comments section you seem to have used the WebForms view engine in your actual code ( <%= Html.Encode(Session["UserName"]) %> ). 根据评论部分,您似乎在实际代码中使用了WebForms视图引擎( <%= Html.Encode(Session["UserName"]) %> )。

This being said you have a far more serious issue with this code. 这就是说这个代码有一个更严重的问题。 The currently authenticated user should never be passed as parameter. 不应将当前经过身份验证的用户作为参数传递。 That's a huge security vulnerability. 这是一个巨大的安全漏洞。 So start by getting rid of it: 所以从摆脱它开始:

<img alt="" src="@Url.Action("GetPhoto", "User")" height="50" width="50" class="photo" />

and then inside your controller action you could retrieve it: 然后在你的控制器动作内你可以检索它:

public ActionResult GetPhoto()
{
    string user = Session["UserName"] as string;
    byte[] photo = db
        .tblUsers
        .Where(p => p.UserName == user)
        .Select(img => img.Photo)
        .FirstOrDefault();
    return File(photo, "image/jpeg");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM