Skip to main content
 首页 » 编程设计

c#之获取 session 值之ASP.NET Web 处理程序文件

2024年01月01日43sharpest

我无法在 ASHX 文件中获取 session 值。
我搜索了here这样我就可以解决我的问题。

但我仍然无法获取 session 值。 请让我得到你的建议。

[ASPX 设计文件]

... 
<form id="form1" runat="server"> 
<div> 
    <iframe runat="server" id="iframepdf" height="600" width="800" src="./PDFViewer.ashx"></iframe> 
</div> 
</form> 
... 

[ASPX 代码隐藏]

... 
namespace WebApplication1 
{ 
public partial class NameCard : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    {    
        Session["PDFFileName"] = @"D:\Test.pdf"; 
    } 
} 
} 

如您所见,我的代码隐藏在文件中,
我为 session 对象设置了一些值。
然后,我在 ashx 文件下面写下。

[ASHX 代码隐藏]

... 
namespace WebApplication1 
{ 
public class PDFViewer : IHttpHandler, System.Web.SessionState.IRequiresSessionState 
{ 
    public void ProcessRequest(HttpContext context) 
    {    
        context.Session["StackOverflow"] = "overflowing";  // This one give me output value as "overflowing" 
        if (context.Session["PDFFileName"] != null) {  // My problem is this line, It always say null value ... 
            context.Response.ContentType = "Application/pdf"; 
            var PDFFileName = context.Session["PDFFileName"].ToString();                 
            context.Response.WriteFile(PDFFileName); 
            context.Response.End(); 
            context.Session["PDFFileName"] = string.Empty; 
        } 
 
    } 
 
    public bool IsReusable 
    { 
        get 
        { 
            return false; 
        } 
    } 
} 
} 

请您参考如下方法:

通过阅读您代码中的注释,我认为您获得了 context.Session["StackOverflow"] 而不是 ["PDFFileName"] 值?那是对的吗?在分配 session 值的页面和使用它们的处理程序中放置断点并运行调试器。

也许您拼错了键?请记住,键是区分大小写的。