将css文件添加到OWIN SelfHost

时间:2016-02-25 08:09:16

标签: c# owin

对于我在C#的实习,我要为现有应用程序创建嵌入式监控,我在Owin SelfHost服务中编写了整个“应用程序”,以使其可用且不依赖于当前这些应用程序的体系结构,我的服务器是使用此代码段启动的:

public void Configuration(IAppBuilder appBuilder)
{
    var configuration = new HttpConfiguration();

    configuration.Routes.MapHttpRoute(
        name: "DefaultRoute",
        routeTemplate: "{controller}/{action}",
        defaults: new { controller = "Monitoring", action = "Get" }
     );

    appBuilder.UseWebApi(configuration);
}

 WebApp.Start<Startup>("http://localhost:9000");

我还为此监控提供了一个图形界面,我正在使用HttpResponseMessage来执行此操作,并使用此代码简单地编写HTML内容。

public HttpResponseMessage GetGraphic()
{
    var response = new HttpResponseMessage()
    {
        Content = new StringContent("...")
    };

    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

现在的问题是我想要将样式添加到当前界面,我将它们放在与项目其余部分相同的目录中(所有内容都存储在这些其他应用程序的子文件夹中,称为{{1} })问题是这些文件不在新的托管服务上,我仍然可以使用Monitoring访问它们,但我想将它们放在projetUrl/Monitoring/file上,因为实际上,这会导致我http://localhost:9000/file尝试加载字体文件时出错。

是否有可能,如果可以,怎么样?

2 个答案:

答案 0 :(得分:1)

这样的事情会起作用吗??

public HttpResponseMessage GetStyle(string name)
{
    var response = new HttpResponseMessage()
    {
        Content = GetFileContent(name)
    };

    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/css");
    return response;
}

private StringContent GetFileContent(string name)
{
    //TODO: fetch the file, read its contents
    return new StringContent(content);
}

请注意,您可以打开一个流来阅读GetFileContents方法中的文件内容。您甚至可以为该操作方法添加一些缓存方法。此外,您可以获得创意,而不是采用一个单独的字符串参数,您可以采取它们的数组并捆绑响应

答案 1 :(得分:1)

我终于使用UseStaticFiles()来处理这种情况,感谢Callumn Linington的想法,我不知道这样的事情是存在的!

以下是我用于潜在未来寻求者的代码:

appBuilder.UseStaticFiles(new StaticFileOptions()
{
    RequestPath = new PathString("/assets"),
    FileSystem = new PhysicalFileSystem(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Monitoring/static"))
});