访问用户控件cs中的通用处理程序?

时间:2011-10-24 08:08:58

标签: c# asp.net .net

我已经制作了一个通用处理程序.ashx,它位于root。

在我的UserControls文件夹中,我有一个用户控件,想要访问这个ashx类的静态方法。但我无法访问ashx类或其方法。它是否需要任何引用或注册?

ashx代码:

    <%@ WebHandler Language="C#" Class="GetTileImage" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
using System.Net;
public class GetTileImage : IHttpHandler, IRequiresSessionState
{
    const string c_key = "dzi";
    public void ProcessRequest(HttpContext context)
    {
        //context.Response.Cache.SetMaxAge(TimeSpan.FromMinutes(60));  
    }
    public bool IsReusable
    {
        get
        {
            return true;
        }
    }

    public static Bitmap LoadImage(string imageUrl)
    {
        Dictionary<string, Bitmap> images = (Dictionary<string, Bitmap>)HttpContext.Current.Session[c_key];
        if (images == null)
        {
            images = new Dictionary<string, Bitmap>();
            HttpContext.Current.Session[c_key] = images;
        }
        Bitmap bmp = null;
        if (!images.ContainsKey(imageUrl))
        {
            try
            {
                string url = imageUrl;
                if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
                    url = HttpContext.Current.Server.MapPath(url); WebClient wc = new WebClient(); Stream fs = wc.OpenRead(url); bmp = new Bitmap(fs); fs.Close();
            }
            catch { return null; }
        } images.Add(imageUrl, bmp); if (images.Count > 5)
        {
            Dictionary<string, Bitmap>.KeyCollection.Enumerator e = images.Keys.GetEnumerator();
            e.MoveNext();
            string key = e.Current;
            images.Remove(key);
        }
        return bmp;
    }
}

用户控制我在哪里访问:

 Bitmap bmp = GetTileImage.LoadImage("");

帮助PLZ

3 个答案:

答案 0 :(得分:1)

除非您为该类添加命名空间,否则我认为您无法从其他地方调用代码:

namespace MyNamespace 
{

    public class GetTileImage : IHttpHandler, IRequiresSessionState
    {
    // etc. etc.
    }

}

MyNamespace应替换为您用于其余代码的任何名称空间。

在任何情况下,我都有点疑惑为什么这个代码完全在.ashx中 - 因为它代表,因为ProcessRequest没有代码,处理程序实际上不会做任何事情。

答案 1 :(得分:1)

不,你无法在后面的代码中访问Generic处理程序类方法(aspx,ascx等)。您必须在App_Code文件夹下创建一个静态(不必要)的类(文件),并在其中移动此方法。

public class GetTileImage
{
 public static Bitmap LoadImage(string imageUrl)
    {
     ..
    }
}

答案 2 :(得分:0)

我认为这可能只是因为您的代码在您的ASHX文件中,如果您使用代码隐藏文件它应该没问题。 e.g:

GetTileImage.ashx:

<%@ WebHandler Language="C#" CodeBehind="GetTileImage.ashx.cs" Class="MyNamespace.GetTileImage" %>

GetTileImage.ashx.cs:

// < using statements here...>

namespace MyNamespace
{
    public class GetTileImage: IHttpHandler
    {
         // < include necessary overrides... >

         public static Bitmap LoadImage()
         {
             // < code here... >
         }
    }
}

然后您应该发现可以在代码中的其他位置调用GetTileImage.LoadImage(此处测试正常)。正如已经指出的那样,最好将LoadImage移动到您的处理程序和UserControls都将使用的实用程序类中。