开发者

How can I detect a child request?

I am trying to create an HttpModule in C# which will redirect arbitrary URLs and missing files, and which will perform canonicalization on all URLs that come in. Part of my canonicalization process is to redirect from default documents (such as http://www.contoso.com/default.aspx) to a bare directory. (like http://www.contoso.com/)

I have discovered that when an IIS server receives a request for a bare directory, it processes this request normally, and then it creates a child request for the selected default document. This is producing a redirect loop in my module - the first request goes through just fine, but when it sees the child request it remo开发者_C百科ves the default document from the url and redirects back to the bare directory, starting the process over again.

Obviously, all I need to solve this problem is for my module to know when it's seeing a child request, so that it can ignore it. But I cannot find anything online describing how to tell the two requests apart. I found that request headers persist between the two requests, so I tried adding a value to the request headers and then looking for that value. This worked in IIS 7, but apparently IIS 6 won't let you alter request headers, and my code needs to run in both.


These child requests can also be triggered by any Server.Transfer or Server.Executes in the code. One trick that works to detect a child request would be to add a custom request header during the first request and checking for it later (when in the child request). Example:

private bool IsChildRequest(HttpRequest request)
{
  var childRequestHeader = request.Headers["x-parent-breadcrumb"];
  if (childRequestHeader != null) 
  {
    return true;
  }

  request.Headers["x-parent-breadcrumb"] = "1"; // arbitrary value
  return false;
}

This works because the request headers are passed to the child request. I initially tried this with HttpContext.Current.Items, but that seemed to get reset for the child request.


What's happening with your module is perfectly the way it should. If your default page is Default.aspx, then IIS is bound to redirect to Default.aspx, which causes your module to redo the work. However one thing I don't understand is that why would you want to have http://www.contoso.com/default.aspx to be redirected to http://www.contoso.com? probably you need to redefine your requirement. Or else, if possible you could have another default page (like http://www.contoso.com/Home.aspx) and then your IIS should forward the bare requests to that URL.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜