2016-02-25 50 views
0

对于我在C#中的实习,我必须为现有应用程序创建一个嵌入式监视器,我在Owin SelfHost服务中编写了整个“应用程序”以使其可用并且不依赖于当前体系结构这些应用程序,我的服务器是在这个片段中推出:将css文件添加到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做到这一点,simpmly写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

是否有可能,如果是的话,如何?

+0

你可以尝试沿着这行的东西:http://stackoverflow.com/questions/35509588/asp-net-core-serving- specific-html-page可以创建中间件来响应某些请求。或者,也许有一些'app.UseStaticFiles()'。 –

回答

1

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

下面是我用于未来潜在的求职者代码:

appBuilder.UseStaticFiles(new StaticFileOptions() 
{ 
    RequestPath = new PathString("/assets"), 
    FileSystem = new PhysicalFileSystem(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Monitoring/static")) 
}); 
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

直接写入响应流不是更好吗? –

+0

@CallumLinington绝对!但只有当你正在接受这个答案时。还有更多的事情可以在这里直接写入响应流,使其变得不可能 – Leo

+0

感谢这一点,但我认为使用静态文件要容易得多! – Sakuto