1

几周前我问了一个关于这个的问题,在这里找到:ServiceStack: URL Re-writing with Self-Hosted application

但是,当我将此应用程序创建为 Windows 服务时遇到了问题。浏览应用程序的根 URL 时出现以下错误:

error CodeFileNotFoundExceptionmessage
Could not find file 'C:\Windows\system32\index.html'.

这是我所做的:

var handleRoot = new CustomActionHandler((httpReq, httpRes) =>
{
    httpRes.ContentType = "text/html";
    httpRes.WriteFile("index.html");
    httpRes.End();
});

SetConfig(new EndpointHostConfig
{
    DebugMode = false,
    RawHttpHandlers =
    {
        httpReq => (httpReq.RawUrl == "/") ? handleRoot : null
    }
});

public class CustomActionHandler : IServiceStackHttpHandler, IHttpHandler
{
    public Action<IHttpRequest, IHttpResponse> Action { get; set; }

    public CustomActionHandler(Action<IHttpRequest, IHttpResponse> action)
    {
        if (action == null)
            throw new Exception("Action was not supplied to ActionHandler");

        Action = action;
    }

    public void ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, string operationName)
    {
        Action(httpReq, httpRes);
    }

    public void ProcessRequest(HttpContext context)
    {
        ProcessRequest(context.Request.ToRequest(GetType().Name),
            context.Response.ToResponse(),
            GetType().Name);
    }

    public bool IsReusable
    {
        get { return false; }
    }
}

如果我把它拿出来并浏览我的服务的根目录,它可以工作,但我已经/index.html附加到最后,因为我希望它就像我将它/作为控制台应用程序托管时一样

4

1 回答 1

3

当您作为 Windows 服务运行时,您的服务的执行目录将成为System32您系统的文件夹,因为这是服务 DLL 主机执行的地方。

这意味着它成为您的 ServiceStack 应用程序的基本目录。因此,如果您这样做httpRes.WriteFile("index.html");,它将查找并看到您的 index.html 不存在index.htmlc:\windows\system32\那里,它将找不到索引。

您可以通过以下两种方式之一解决此问题。您可以设置从中读取文件的基本目录;或者您可以在选择要写入的文件时指定完整路径。

设置当前目录:

通过在应用程序启动时包含此行,您可以将目录更改为执行服务程序集的目录而不是系统目录。

System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
...
httpRes.WriteFile("index.html"); // index.html is read from the application directory now

获取应用目录:

或者您可以确定应用程序目录并将其与 结合index.html以形成完整路径。

var directory = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
httpRes.WriteFile(Path.Combine(directory, "index.html"));
于 2014-05-29T12:33:42.150 回答