ASP.NET MVC - 图像+认证的用户仅

问题描述:

是它可能以某种方式只允许验证的用户查看特定的图像?我建立的那一刻Web画廊,和我不想要非认证用户才能够看到的图像。

is it possible to somehow only allow authenticated users to view certain images? I'm building a web gallery at the moment, and I dont want non-authenticated users to be able to see the images.

您可以把这些图片的地方在服务器上,用户无权访问(例如像在〜/ App_Data文件文件夹),以prevent直接访问它们,然后使用一个控制器动作来为他们服务。这一行动将与授权属性,只允许通过验证的用户调用它来装饰:

You could put those images somewhere on the server where users don't have access (like for example the ~/App_Data folder) in order to prevent direct access to them and then use a controller action to serve them. This action will be decorated with an Authorize attribute to allow only authenticated users to call it:

[Authorize]
public ActionResult Image(string name)
{
    var appData = Server.MapPath("~/App_Data");
    var image = Path.Combine(appData, name + ".png");
    return File(image, "image/png");
}

和则:

<img src="@Url.Action("Image", "SomeController", new { name = "foo" })" alt="" />

视图里面你也可以测试显示图像之前,用户是否经过验证。

Inside the view you could also test whether the user is authenticated before displaying the image.