Specifying exact path for my ASP.NET Http Handler

◇◆丶佛笑我妖孽 提交于 2020-01-03 17:01:02

问题


I generate an XML/Google sitemap on the fly using an Http Handler, so that I don't need to maintain an XML file manually.

I have mapped my Http Handler to "sitemap.xml" in my web.config like this:

<httpHandlers>
  <add verb="*" path="sitemap.xml" type="My.Name.Space, MyAssembly" />
</httpHandlers>

It works nicely. Now, www.mywebsite.com/sitemap.xml sets my Http Handler into action and does exactly what I want. However, this url will do the same: www.mywebsite.com/some/folder/sitemap.xml and I don't really want that i.e. I just want to map my handler to the root of my application.

I have tried changing the "path" of my handler in my web.config to "/sitemap.xml" and "~/sitemap.xml" but neither works.

Am I missing something here?


回答1:


Try adding the following to your web.config

<urlMappings enabled="true">
    <add url="~/SiteMap.xml" mappedUrl="~/MyHandler.ashx"/>
</urlMappings>

This uses a little known feature of ASP.NET 2.0 called 'Url Mapping'




回答2:


Following on from Kirtan suggested solution #1 you can do a workaround like follows:

public void ProcessRequest(HttpContext context) {
  //Ensure that the sitemap.xml request is to the root of the application
  if (!context.Request.PhysicalPath.Equals(Server.MapPath("~/sitemap.xml"))) {
     //Invoke the Default Handler for this Request
     context.RemapHandler(null);
  }

  //Generate the Sitemap
}

You might need to play with this a bit, not sure if invoking the default handler will just cause IIS to re-invoke your Handler again. Probably worth testing in Debug mode from VS. If it does just re-invoke then you'll need to try invoking some static file Handler instead or you could just issue a HTTP 404 yourself eg

//Issue a HTTP 404
context.Response.Clear();
context.Response.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
return;

See the MSDN documentation on HttpContext.RemapHandler for more info - http://msdn.microsoft.com/en-us/library/system.web.httpcontext.remaphandler.aspx




回答3:


2 solutions to this:

Soln #1: You can check the request path using the Request.Url property, if the request is from the root path, you can generate the XML, else don't do anything.

Soln #2: Put a web.config file with the following setting in every folder in which you don't want to handle the request for the sitemap.xml file.




回答4:


You can, alternately, run a check in the global.asax, verify the request, and finaly re-assigning a new handler throughtout context.RemapHandler method.
The only thing is that you would´ve to implement a factory for that matter.

I would suggest you inherit the HttpApplication, and implement there the factory, but that's your call.



来源:https://stackoverflow.com/questions/700443/specifying-exact-path-for-my-asp-net-http-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!