简体   繁体   English

ASP.NET MVC - 仅限图像+经过身份验证的用户

[英]ASP.NET MVC - Image + Authenticated Users Only

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. 我正在建立一个网络图库,我不希望未经过身份验证的用户能够看到图像。

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. 您可以将这些图像放在用户无权访问的服务器上(例如~/App_Data文件夹),以防止直接访问它们,然后使用控制器操作来为它们提供服务。 This action will be decorated with an Authorize attribute to allow only authenticated users to call it: 此操作将使用Authorize属性进行修饰,以仅允许经过身份验证的用户调用它:

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

and then: 然后:

<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. 在视图内部,您还可以在显示图像之前测试用户是否经过身份验证。

Yes it is possible to hide images from unauthenticated users. 是的,可以隐藏未经身份验证的用户的图像。

Depending on how your images are being displayed, you might hide them through 根据图像的显示方式,您可以隐藏它们

1.using the Authorize attribute on the controller action 1.使用控制器操作的Authorize属性

2.wrapping the HTML in the view that will display the images in 2.在将显示图像的视图中包装HTML

if (User.Identity.IsAuthenticated) {
    // image HTML here   
}

You'll want to put the images somewhere where they cannot be viewed without being authenticated, such as in App_Data as Darin suggests. 如果没有经过身份验证,您可能希望将图像放在无法查看的位置,例如在Darin建议的App_Data中。

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

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