.net 中ashx处理接口 ihttphandler是否servlet线程安全吗

温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
谋而后动 动必有成
LOFTER精选
原后来查了一下。发现原因是在自定义http处理程序操作会话是没有相应的权限。继承IRequiresSessionState接口。msdn上解释为:为自定义http处理程序操作会话赋予权限。为标记接口。本人猜测本质问题其实就是自定义的http处理程序没有操作权限可能是为了安全性考虑做出的一种避免措施&%@ WebHandler Language="C#" Class="GetSeesion" %&using Susing System.Wusing System.Web.SessionSpublic class GetSeesion : IHttpHandler, IRequiresSessionState{
public void ProcessRequest(HttpContext context)
context.Response.ContentType = "text/plain";
//context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
if (context.Session["AdminName"] != null)
context.Response.Write("{name:'" + context.Session["AdminName"].ToString() + "'}");
context.Response.Write("{name:'" + "Session is null" + "'}");
public bool IsReusable
$(function () {
//要用post方式
type: "Post",
//方法所在页面和方法名
url: "GetSeesion.ashx",
contentType: "application/ charset=utf-8",
dataType: "json",
success: function (data) {
//返回的数据用data.d获取内容
alert(data.d);
error: function (err) {
alert(err.responseText);
阅读(574)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
在LOFTER的更多文章
loftPermalink:'',
id:'fks_',
blogTitle:'ASP.NET中ashx页面获取sesion始终为null的解决办法',
blogAbstract:'ashx页面如下。之前一直获取不到session。网上查了很多有说是缓存的问题。就是代码中注释的那一行、后来发现也不行。原后来查了一下。发现原因是在自定义http处理程序操作会话是没有相应的权限。继承IRequiresSessionState接口。msdn上解释为:为自定义http处理程序操作会话赋予权限。为标记接口。本人猜测本质问题其实就是自定义的http处理程序没有操作权限可能是为了安全性考虑做出的一种避免措施&%@ WebHandler Language=\"C#\" Class=\"GetSeesion\" %&',
blogTag:'',
blogUrl:'blog/static/',
isPublished:1,
istop:false,
modifyTime:9,
publishTime:6,
permalink:'blog/static/',
commentCount:0,
mainCommentCount:0,
recommendCount:0,
bsrk:-100,
publisherId:0,
recomBlogHome:false,
currentRecomBlog:false,
attachmentsFileIds:[],
groupInfo:{},
friendstatus:'none',
followstatus:'unFollow',
pubSucc:'',
visitorProvince:'',
visitorCity:'',
visitorNewUser:false,
postAddInfo:{},
mset:'000',
remindgoodnightblog:false,
isBlackVisitor:false,
isShowYodaoAd:false,
hostIntro:'谋而后动 动必有成',
hmcon:'0',
selfRecomBlogCount:'0',
lofter_single:''
{list a as x}
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}web程序时,当使用session时总会出现失效而报&未将对象引用设置到对象的实例&的http 500错误,本人比较懒,不想每个地方都用try catch处理,就找到个用httpModule统一处理的方法:
1、新建一个_httpmodule的类,继承IHttpModule接口,为了能在类里面读取session,添加using System.Web.SessionS,并继承IReadOnlySessionState接口;
2、添加application的AcquireRequestState处理:
void context_AcquireRequestState(object sender, EventArgs e)
HttpApplication application = (HttpApplication)
HttpContext context = application.C
context_AcquireRequestState(context, new EventArgs());
void context_AcquireRequestState(HttpContext context, EventArgs e)
if (!context.Request.Path.ToString().Contains("login.aspx"))
context.Session["loginUser"].ToString();
catch (Exception ex)
context.Response.Write("{'error':false,'message':'尚未登录!'}");
context.Response.End();
3、添加init,里面注册AcquireRequestState事件:
public void Init(HttpApplication context)
context.AcquireRequestState += new EventHandler(context_AcquireRequestState);
4、webconfig &system.web&节配置:
&httpModules&
&add name="123" type="_httpmodule"/&
&/httpModules&
这样当session失效的时候放回错误信息,前台ajax处理返回Json即可。
ps:刚开始我将2、3注册成BeginRequest,可是总取不到Session中的用户信息,&搜索后发现一篇blog(),转载如下:
可是,别忙,怎么总取不到Session中的用户信息呢?记录访问日志用户Id这样的信息肯定是需要记录的啊!
后来放狗一搜才发现,还是对aspnet的事件处理流程不理解,Begin_Request时还没有加载Session状态呢,自然就取不到了。
下面是上提供的事件触发顺序:
在处理该请求时将由 HttpApplication 类执行以下事件。希望扩展 HttpApplication 类的开发人员尤其需要注意这些事件。
对请求进行验证,将检查浏览器发送的信息,并确定其是否包含潜在恶意标记。有关更多信息,请参见
如果已在 Web.config 文件的
节中配置了任何 URL,则执行 URL 映射。
根据所请求资源的文件扩展名(在应用程序的配置文件中映射),选择实现
的类,对请求进行处理。如果该请求针对从
类派生的对象(页),并且需要对该页进行编译,则 ASP.NET 会在创建该页的实例之前对其进行编译。
为该请求调用合适的 IHttpHandler 类的
方法(或异步版 )。例如,如果该请求针对某页,则当前的页实例将处理该请求。
如果定义了
属性,则执行响应筛选。
AcquireRequestState事件,当实际服务请求的处理程序获得与该请求关联的状态信息时发生。在这个事件发生时才能取到Session中是userId信息。BeginRequest事件在AcquireRequestState之前发生,我们把取Session状态的代码放在BeginRequest中肯定是取不到的。
问题找到了,把日志记录代码放在AcquireRequestState中就可以了,于是改成下面的样子:
public void Init(HttpApplication context){&&& context.AcquireRequestState += new EventHandler(context_AcquireRequestState);}
void context_AcquireRequestState(object sender, EventArgs e){
& //原先context_BeginRequest中的代码,不重复贴占地方了 :)
//把LogEntry中的信息保存到数据库
好了,这样我们继承了IHttpModule接口,实现了一个自定义的LogMudule,这样在用户方面每个页面时,都会自动记录用户的信息记如访问日志数据库中,再也不用到每个页面的Page_Load中去写了,维护起来也方便多了! Yeah~
阅读(...) 评论()可以ASP.NET路由被用于创建。ashx的(IHttpHander)处理“干净”的网址?
我有REST普通的旧IHttpHandler秒。我想产生更清洁的URL,这样我就不用了。ashx的路径。有没有一种方法ASP.NET路由来创建映射到ashx的处理路线?我已经看到了这些类型的路由
// Route to an aspx page
RouteTable.Routes.MapPageRoute("route-name",
"some/path/{arg}",
"~/Pages/SomePage.aspx");
// Route for a WCF service
RouteTable.Routes.Add(new ServiceRoute("Services/SomeService",
new WebServiceHostFactory(),
typeof(SomeService)));
尝试RouteTable.Routes.MapPageRoute()产生错误(该处理程序不派生自Page)。System.Web.Routing.RouteBase唯一似乎有2个派生类:ServiceRoute供服务,并且DynamicDataRouteMVC的。我不知道是什么MapPageRoute()并(反射不显示体,它只是显示“性能的关键跨越的NGen图像borderinline这种类型的”)。
我看到RouteBase不密封,并具有相对简单的接口:
public abstract RouteData GetRouteData(HttpContextBase httpContext);
public abstract VirtualPathData GetVirtualPath(RequestContext requestContext,
RouteValueDictionary values);
所以也许我可以做我自己的HttpHandlerRoute。我给了一个镜头,但如果有人知道的映射路线IHttpHandlers现有的或内置的方式,那将是巨大的。
本文地址 :CodeGo.net/180476/
-------------------------------------------------------------------------------------------------------------------------
1. 好吧,我已经搞清楚了这一点,因为我本来问这个问题,我终于有没有我想要的东西的解决方案。达阵的解释有点到期,但是。 IHttpHandler的是一个非常基本的接口:
bool IsReusable { }
void ProcessRequest(HttpContext context)
没有内置的属性,用于访问路径数据,和路由数据也不能在上下文或请求中找到.aSystem.Web.UI.Page对象有一个RouteData物业 CodeGo.net,ServiceRoute来做解释你的UriTemplates并传递值到内部的各项工作,和ASP.NET MVC提供了它自己的访问路径数据的方式。即使你有一个RouteBase即(一)确定如果URL是的路线及(b)解析链接直接从您的IHttpHandler中提取所有的单个值来,有没有简单的方法来这条路线数据传递给你的IHttpHandler的。如果你想保持你的IHttpHandler“纯”,可以这么说,它需要处理的URL的责任,以及如何从中提取任何值。在这种情况下创建RouteBase是为了确定您的IHttpHandler应该不惜一切。
然而,一个问题仍然存在.a旦创建RouteBase确定URL是一个匹配你的路线,它给了IRouteHandler,它创建了IHttpHandler的要处理您的请求的情况下通过了。但是,一旦你在你的IHttpHandler,价值context.Request.CurrentExecutionFilePath是一种误导。它的URL,从客户端端中,查询字符串。所以它不是的路径。ashx的文件。而且,你的路线是恒定的(如任何部分将是执行文件的路径值的一部分。这可能是一个问题,如果你的IHttpHandler内UriTemplates确定哪个IHttpHandler的内应移交的请求。
例如:如果你在/ myApp的/服务/ myHelloWorldHandler.ashx有一个ashx的处理程序。
而且你有这个路由映射到处理程序:“服务/你好/ {
而你导航到这个网址,试图调用SayHello(string name)您的处理方法:
那么你的CurrentExecutionFilePath将是:/ myApp的/服务/你好/山姆。它包括路由URL,这是一个问题的部件。你想要的执行文件路径,以匹配您的路由URL。的下面RouteBase和IRouteHandler处理这个问题。
之前我贴的2班,这里有一个很的例子。请注意,这些创建RouteBase和了IRouteHandler将用于IHttpHandlers甚至不具有。ashx的文件,这是非常方便的实际工作。
// A "headless" IHttpHandler route (no .ashx file required)
RouteTable.Routes.Add(new GenericHandlerRoute&HeadlessService&("services/headless"));
将所有URL匹配“服务/headless”的路线将被切换到的一个新实例HeadlessService的IHttpHandler(HeadlessService就是在这种情况下的例子。这将是任何的IHttpHandler你想传递给过)。
好了,这里有类路由和所有:
/// &summary&
/// For info on subclassing RouteBase, check Pro Asp.NET MVC Framework, page 252.
/// Google books link:
CodeGo.net
/// It explains how the asp.net runtime will call GetRouteData() for every route in the route table.
/// GetRouteData() is used for inbound url matching, and should return null for a negative match (the current requests url doesn't match the route).
/// If it does match, it returns a RouteData object describing the handler that should be used for that request, along with any data values (stored in RouteData.Values) that
/// that handler might be interested in.
/// The book also explains that GetVirtualPath() (used for outbound url generation) is called for each route in the route table, but that is not my experience,
/// as mine used to simply throw a NotImplementedException, and that never caused a problem for me. In my case, I don't need to do outbound url generation,
/// so I don't have to worry about it in any case.
/// &/summary&
/// &typeparam name="T"&&/typeparam&
public class GenericHandlerRoute&T& : RouteBase where T : IHttpHandler, new()
public string RouteUrl { }
public GenericHandlerRoute(string routeUrl)
RouteUrl = routeU
public override RouteData GetRouteData(HttpContextBase httpContext)
// See if the current request matches this route's url
string baseUrl = httpContext.Request.CurrentExecutionFileP
int ix = baseUrl.IndexOf(RouteUrl);
if (ix == -1)
// Doesn't match this route. Returning null indicates to the asp.net runtime that this route doesn't apply for the current request.
baseUrl = baseUrl.Substring(0, ix + RouteUrl.Length);
// This is kind of a hack. There's no way to access the route data (or even the route url) from an IHttpHandler (which has a very basic interface).
// We need to store the "base" url somewhere, including parts of the route url that are constant, like maybe the name of a method, etc.
// For instance, if the route url "myService/myMethod/{myArg}", and the request url were " CodeGo.net
// the "current execution path" would include the "myServer/myMethod" as part of the url, which is incorrect (and it will prevent your UriTemplates from matching).
// Since at this point in the exectuion, we know the route url, we can calculate the true base url (excluding all parts of the route url).
// This means that any IHttpHandlers that use this routing mechanism will have to look for the "__baseUrl" item in the HttpContext.Current.Items bag.
// TODO: Another way to solve this would be to create a subclass of IHttpHandler that has a BaseUrl property that can be set, and only let this route handler
// work with instances of the subclass. Perhaps I can just have RestHttpHandler have that property. My reticence is that it would be nice to have a generic
// route handler that works for any "plain ol" IHttpHandler (even though in this case, you have to use the "global" base url that's stored in HttpContext.Current.Items...)
// Oh well. At least this works for now.
httpContext.Items["__baseUrl"] = baseU
GenericHandlerRouteHandler&T& routeHandler = new GenericHandlerRouteHandler&T&();
RouteData rdata = new RouteData(this, routeHandler);
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
// This route entry doesn't generate outbound Urls.
public class GenericHandlerRouteHandler&T& : IRouteHandler where T : IHttpHandler, new()
public IHttpHandler GetHttpHandler(RequestContext requestContext)
return new T();
我知道这个答案已经很长篇大论,但它不是一个容易解决的问题。核心逻辑是很容易,关键是让你的IHttpHandler知道“基本URL”,所以,它可以正确地确定哪些URL的一部分属于路径,以及哪些部分是实际的服务调用。
这些课程将在我的C#的REST库,RestCake。我希望我的道路向下路由兔子洞将帮助其他人谁决定创建RouteBase,并做很酷的东西与IHttpHandlers。
其实我喜欢乔尔的解决方案更好,因为它不需要你知道处理程序的类型你想设置你的路由,而。我的upvote它,但很可惜,我没有所需的声誉。
在这里,我居然发现,我的感觉是比原来的源代码中,我得出我的例子从一个更好的解决方案,可以发现链接
这是更少的代码,类型无关,和快速。
public class HttpHandlerRoute : IRouteHandler {
private String _VirtualPath =
public HttpHandlerRoute(String virtualPath) {
_VirtualPath = virtualP
public IHttpHandler GetHttpHandler(RequestContext requestContext) {
IHttpHandler httpHandler = (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath(_VirtualPath, typeof(IHttpHandler));
return httpH
和一个粗略的例子
String handlerPath = "~/UploadHandler.ashx";
RouteTable.Routes.Add(new Route("files/upload", new HttpHandlerRoute(handlerPath)));
是的,我注意到了。也许有一个内置的ASP.NET的方式来做到这一点,但关键是要建立从了IRouteHandler派生一个新类:
using System.IO;
using System.R
using System.Text.RegularE
using System.W
using System.Web.R
namespace MyNamespace
class GenericHandlerRouteHandler : IRouteHandler
private string _virtualP
private Type _handlerT
private static object s_lock = new object();
public GenericHandlerRouteHandler(string virtualPath)
_virtualPath = virtualP
#region IRouteHandler Members
public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext)
ResolveHandler();
IHttpHandler handler = (IHttpHandler)Activator.CreateInstance(_handlerType);
#endregion
private void ResolveHandler()
if (_handlerType != null)
lock (s_lock)
// determine physical path of ashx
string path = _virtualPath.Replace("~/", HttpRuntime.AppDomainAppPath);
if (!File.Exists(path))
throw new FileNotFoundException("Generic handler " + _virtualPath + " could not be found.");
// parse the class name out of the .ashx file
// unescaped reg-ex: (?&=Class=")[a-zA-Z\.]*
string classN
Regex regex = new Regex("(?&=Class=\")[a-zA-Z\\.]*");
using (var sr = new StreamReader(path))
string str = sr.ReadToEnd();
Match match = regex.Match(str);
if (match == null)
throw new InvalidDataException("Could not determine class name for generic handler " + _virtualPath);
className = match.V
// get the class type from the name
Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly asm in asms)
_handlerType = asm.GetType(className);
if (_handlerType != null)
if (_handlerType == null)
throw new InvalidDataException("Could not find type " + className + " in any loaded assemblies.");
要创建一个ashx的一个途径。:
IRouteHandler routeHandler = new GenericHandlerRouteHandler("~/somehandler.ashx");
Route route = new Route("myroute", null, null, null, routeHandler);
RouteTable.Routes.Add(route);
上面的代码中,可能需要提高你的工作路线,但它的出发点。
所有这些答案都非常好。我爱先生米查姆的简单性GenericHandlerRouteHandler&T&类。这是一个伟大的想法,消除不必要的引用一个虚拟路径,如果你知道具体的HttpHandler类。该GenericHandlerRoute&T&类不是自己的需要。现有Route派生类从RouteBase已处理所有的路由匹配等的,所以我们可以把它连同GenericHandlerRouteHandler&T&。
下面是版采用了真实的例子,包括路线
首先是路由处理程序。有两个在内,在这里-无论是带班,而且是一个通用的创建具体的实例HttpHandler如米查姆先生“和一个虚拟路径和BuildManager创建适当的实例HttpHandler在shellscape“好消息是,.NET允许既共处就好了,所以我们可以取其我们想要的和我们希望他们之间可以切换。
using System.W
using System.Web.R
public class HttpHandlerRouteHandler&T& : IRouteHandler where T : IHttpHandler, new() {
public HttpHandlerRouteHandler() { }
public IHttpHandler GetHttpHandler(RequestContext requestContext) {
return new T();
public class HttpHandlerRouteHandler : IRouteHandler {
private string _VirtualP
public HttpHandlerRouteHandler(string virtualPath) {
this._VirtualPath = virtualP
public IHttpHandler GetHttpHandler(RequestContext requestContext) {
return (IHttpHandler) BuildManager.CreateInstanceFromVirtualPath(this._VirtualPath, typeof(IHttpHandler));
让我们创建一个HttpHandler该流从资源我们的虚拟文件夹之外,甚至从一个数据库,我们要欺骗浏览器,以为我们是直接服务于一个特定的文件,而不是简单地提供一个下载(即,允许浏览器的插件来处理该文件而不是强迫来保存文件)。该HttpHandler可能expect一个ID,以供定位提供,并可能expect一个文件,以提供给浏览器-一个可能不同于服务器上使用的文件。
下面展示的这一个登记DocumentHandlerHttpHandler:
routes.Add("Document", new Route("document/{documentId}/{*fileName}", new HttpHandlerRouteHandler&DocumentHandler&()));
{*fileName}而不是仅仅{fileName}以允许fileName作为一个可选的catch-all
要创建该送达文件的URLHttpHandler,我们可以添加以下一类的地方,例如将是适当的,如在HttpHandler类,本身:
public static string GetFileUrl(int documentId, string fileName) {
string mimeType =
try { mimeType = MimeMap.GetMimeType(Path.GetExtension(fileName)); }
RouteValueDictionary documentRouteParameters = new RouteValueDictionary { { "documentId", documentId.ToString(CultureInfo.InvariantCulture) }
, { "fileName", DocumentHandler.IsPassThruMimeType(mimeType) ? fileName : string.Empty } };
return RouteTable.Routes.GetVirtualPath(null, "Document", documentRouteParameters).VirtualP
我省略的定义MimeMap和和IsPassThruMimeType保持这个例子简单。但这些是为了确定是否特定的文件类型应该在URL中直接提供他们的文件,或者更确切地说,在一Content-DispositionHTTP标头。文件扩展名可以由IIS或URL扫描受阻,或可能的代码来执行可能的问题-尤其是如果该文件的来源是谁是你可以与其他的过滤逻辑取代这个逻辑,或省略这样的逻辑完全是,如果你不面对这种类型的风险。
因为在这个特定的例子中,文件可被从URL中省略,那么,就必须从在该特定示例中检索该文件,该文件可以通过执行一个查找的id,并包括在URL中的文件进行检索的目的仅仅是对改善体验。所以,本DocumentHandlerHttpHandler可以判断一个文件是在URL中提供的,如果它不是,那么它可以简单地添加一个Content-DispositionHTTP头的响应。
停留在主题,上面的代码块的重要组成部分,是RouteTable.Routes.GetVirtualPath()和路由从产生的URLRoute反对说,我们在路由注册过程中创建的。
这里是的一个简化版本DocumentHandlerHttpHandler类(多省略为清楚起见)。你可以看到,这条路线检索id和文件时,它可以,否则,它会尝试从一个查询字符串(即获取ID,假设路由被
public void ProcessRequest(HttpContext context) {
context.Response.Clear();
// Get the requested document ID from routing data, if routed. Otherwise, use the query string.
bool isRouted =
int? documentId =
string fileName =
RequestContext requestContext = context.Request.RequestC
if (requestContext != null && requestContext.RouteData != null) {
documentId = Utility.ParseInt32(requestContext.RouteData.Values["documentId"] as string);
fileName = Utility.Trim(requestContext.RouteData.Values["fileName"] as string);
isRouted = documentId.HasV
// Try the query string if no documentId obtained from route parameters.
if (!isRouted) {
documentId = Utility.ParseInt32(context.Request.QueryString["id"]);
fileName =
if (!documentId.HasValue) { // Bad request
// Response logic for bad request omitted for sake of simplicity
DocumentDetails documentInfo = ... // Details of loading this information omitted
if (context.Response.IsClientConnected) {
string fileExtension = string.E
try { fileExtension = Path.GetExtension(fileName ?? documentInfo.FileName); } // Use file name provided in URL, if provided, to get the extension.
// Transmit the file to the client.
FileInfo file = new FileInfo(documentInfo.StoragePath);
using (FileStream fileStream = file.OpenRead()) {
// If the file size exceeds the threshold specified in the system settings, then we will send the file to the client in chunks.
bool mustChunk = fileStream.Length & Math.Max(SystemSettings.Default.MaxBufferedDownloadSize * 1024, DocumentHandler.SecondaryBufferSize);
// WARNING! Do not ever set the following property to false!
Doing so causes each chunk sent by IIS to be of the same size,
even if a chunk you are writing, such as the final chunk, may
be shorter than the rest, causing extra bytes to be written to
the stream.
context.Response.BufferOutput =
context.Response.ContentType = MimeMap.GetMimeType(fileExtension);
context.Response.AddHeader("Content-Length", fileStream.Length.ToString(CultureInfo.InvariantCulture));
if ( !isRouted
|| string.IsNullOrWhiteSpace(fileName)
|| string.IsNullOrWhiteSpace(fileExtension)) { // If routed and a file name was provided in the route, then the URL will appear to point directly to a file, and no file n otherwise, add the header.
context.Response.AddHeader("Content-Disposition", string.Format(" filename={0}", HttpUtility.UrlEncode(documentInfo.FileName)));
bufferSize
= DocumentHandler.SecondaryBufferS
byte[] buffer
= new byte[bufferSize];
while ((bytesRead = fileStream.Read(buffer, 0, bufferSize)) & 0 && context.Response.IsClientConnected) {
context.Response.OutputStream.Write(buffer, 0, bytesRead);
if (mustChunk) {
context.Response.Flush();
catch (Exception e) {
// Error handling omitted from this example.
这种额外的自定义类,如Utility类来简化琐碎的任务。但希望你可以通过杂草。当然,就目前的主题在这个类中唯一真正重要的组成部分,是路由从检索context.Request.RequestContext.RouteData。但我见过几个post其他要求如何流的大HttpHandler不嚼起来所以它是一个好主意的例子。
编辑:我刚才编辑这个代码我有问题的旧的。如果你是旧版本,请更新。
这个线程是有点老,但我只是重新写这里的代码做的事情,但在一个更优雅的方式,使用
我在Web表单这一点,我想对一个文件夹中的ashx的文件,并能够给他们打电话路由或正常请求。
所以,我几乎抓住shellscape的代码并做了该做的伎俩。最后我觉得我也应该支持通过了IHttpHandler对象,而不是它的URL,所以我写了和过载了点。
namespace System.Web.Routing
public class HttpHandlerRoute&T& : IRouteHandler where T: IHttpHandler
private String _virtualPath =
public HttpHandlerRoute(String virtualPath)
_virtualPath = virtualP
public HttpHandlerRoute() { }
public IHttpHandler GetHttpHandler(RequestContext requestContext)
return Activator.CreateInstance&T&();
public class HttpHandlerRoute : IRouteHandler
private String _virtualPath =
public HttpHandlerRoute(String virtualPath)
_virtualPath = virtualP
public IHttpHandler GetHttpHandler(RequestContext requestContext)
if (!string.IsNullOrEmpty(_virtualPath))
return (IHttpHandler)pilation.BuildManager.CreateInstanceFromVirtualPath(_virtualPath, typeof(IHttpHandler));
throw new InvalidOperationException("HttpHandlerRoute threw an error because the virtual path to the HttpHandler is null or empty.");
public static class RoutingExtension
public static void MapHttpHandlerRoute(this RouteCollection routes, string routeName, string routeUrl, string physicalFile, RouteValueDictionary defaults = null, RouteValueDictionary constraints = null)
var route = new Route(routeUrl, defaults, constraints, new HttpHandlerRoute(physicalFile));
routes.Add(routeName, route);
public static void MapHttpHandlerRoute&T&(this RouteCollection routes, string routeName, string routeUrl, RouteValueDictionary defaults = null, RouteValueDictionary constraints = null) where T : IHttpHandler
var route = new Route(routeUrl, defaults, constraints, new HttpHandlerRoute&T&());
routes.Add(routeName, route);
我把它里面的所有本机的路由对象,所以它会自动提供。
所以,这一点,你只需要调用:
// using the handler url
routes.MapHttpHandlerRoute("DoSomething", "Handlers/DoSomething", "~/DoSomething.ashx");
// using the type of the handler
routes.MapHttpHandlerRoute&MyHttpHanler&("DoSomething", "Handlers/DoSomething");
本文标题 :可以ASP.NET路由被用于创建。ashx的(IHttpHander)处理“干净”的网址?
本文地址 :CodeGo.net/180476/
Copyright (C) 2014 CodeGo.net 沪ICP备号 联系电邮: (#=@)

我要回帖

更多关于 c queue 线程安全 的文章

 

随机推荐