
Originariamente inviata da
ciro78
Ciao e grazie.
Fatto ma non mi cambia nulla. La finestra del browser si apre e resta aperta.
Non saprei... puoi descrivere meglio lo scenario?
Io ho provato questo e va, nel senso che funziona come mi aspetto e non apre una nuova scheda ma fa partire il download del file, se c'è e l'utente è autenticato, allora restituisce il file reale (nel link immagine.png), se non autenticato restituisce il file di default (qui default.jpg), mentre se non esiste il file ovviamente restituisce il 404, ma sempre nella stessa scheda senza aprirne altre.
Per completezza ecco tutta la parte interessata:
codice:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="WebApplication.test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="login" />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="logout" />
<a href="images/immagine.png">immagine.png</a>
<a href="images/dasda">not found</a>
</form>
</body>
</html>
codice:
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Auth"] == null)
Session.Add("Auth", false);
}
protected void Button1_Click(object sender, EventArgs e)
{
HttpContext.Current.Session["Auth"] = true;
}
protected void Button2_Click(object sender, EventArgs e)
{
HttpContext.Current.Session["Auth"] = false;
}
}
codice:
public class NoLeechImageHandler: IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(System.Web.HttpContext ctx)
{
HttpRequest req = ctx.Request;
string serverPath = ctx.Server.MapPath(req.FilePath);
if (!File.Exists(serverPath))
{
ctx.Response.StatusDescription = "Image not found";
ctx.Response.StatusCode = 404;
return;
}
string path = (ctx.Session["Auth"] != null && (bool)ctx.Session["Auth"])?
serverPath:
Path.Combine(ctx.Server.MapPath("~/images"), "default.jpg");
ctx.Response.Clear();
ctx.Response.ContentType = "application/octet-stream";
ctx.Response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}", path));
ctx.Response.TransmitFile(path);
ctx.Response.End();
}
public bool IsReusable { get { return true; } }
}