问题
I am trying to understand the PathInfo property of System.Web.HttpRequest and how it is set.
Why would it be empty in the following example?
var p = new System.Web.HttpRequest("file.txt","http://file.com/files/file.txt","");
//PathInfo is always empty
return string.IsNullOrEmpty(p.PathInfo)
I am trying to pipe the Elmah interface through Nancyfx by invoking the Elmah.ErrorLogPageFactory::ProcessRequest(HttpContext context).
but it does not work because Elmah.ErrorLogPageFactory depends on HttpRequest::PathInfo to resolve the correct IHttpHandler and PathInfo is always empty.
If someone would take the time explaining how PathInfo works I would be very grateful!
回答1:
The PathInfo
property is calculated basing on HttpContext
private variable of the HttpRequest
class. There's no official way to set this HttpContext
instance. That's why whenever you create the HttpRequest
manually, the HttpContext
is always null, therefore the PathInfo
use empty also.
To get something different from empty string you need to use a real instance, which is created by .NET framework to you, and not to instantiate it by yourself.
回答2:
I have just been trying to do a similar thing with Elmah.
My route was set up as follows:
var url = "admin/elmah.axd/{*pathInfo}";
var defaults = new RouteValueDictionary {{"pathInfo", string.Empty}};
var routeHandler = new ElmahHandler();
var route = new Route(url, defaults, routeHandler);
RouteTable.Routes.Add(route);
But I too found that the pathinfo is always empty, so the stylesheet and additional paths didn't work. I managed to achieve my goal using reflection to call the underlying methods in the ErrorLogFactory.
private object InvokeMethod(string name, params object[] args)
{
var dynMethod = typeof(ErrorLogPageFactory).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic);
return dynMethod.Invoke(null, args );
}
Then my handler looked like this
public class ElmahHandler : ErrorLogPageFactory, IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var handler = InvokeMethod("FindHandler", requestContext.RouteData.Values["pathInfo"]) as IHttpHandler;
if (handler == null)
throw new HttpException(404, "Resource not found.");
var num = (int)InvokeMethod("IsAuthorized", context);
if (num != 0 && (num >= 0 || HttpRequestSecurity.IsLocal(context.Request) /*|| SecurityConfiguration.Default.AllowRemoteAccess*/))
{
return handler;
}
//new ManifestResourceHandler("RemoteAccessError.htm", "text/html").ProcessRequest(context);
HttpResponse response = context.Response;
response.Status = "403 Forbidden";
response.End();
return null;
}
}
I had no need to get the ManifestResourceHandler working, so just commented it out, likewise for the allowRemoteAccess setting
来源:https://stackoverflow.com/questions/13456586/how-does-system-web-httprequestpathinfo-work