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 b开发者_运维知识库e 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. 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");
}
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
2.wrapping the HTML in the view that will display the images in
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.
精彩评论