将 css 文件添加到 OWIN SelfHost

Add css file to an OWIN SelfHost

为了我在 C# 的实习,我必须为现有应用程序创建一个嵌入式监控,我将整个 "application" 写在一个 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;
}

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

是否可能,如果可能,如何实现?

这样的东西能行得通吗...?

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 方法中打开一个流来读取文件内容。您甚至可以为该操作方法添加一些缓存方法。此外,您可以发挥创意,而不是采用单个字符串参数,您可以采用一组参数并将响应捆绑在一起

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

这是我用于未来潜在搜索者的代码:

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