【问题标题】:Can I create a route which redirects "/" to another folder with static HTML files in it?我可以创建一个将“/”重定向到另一个包含静态 HTML 文件的文件夹的路由吗?
【发布时间】:2014-08-17 16:53:54
【问题描述】:

我正在使用 WebApi,并为“api/{controller}/{id}”设置了路由。但我在项目中也有以下文件夹结构:

\Static\index.html
\Static\pageY.html

我希望网站的用户能够访问:

http://localhost/index.html
http://localhost/pageY.html

这是我应该避免做的事情吗?如果没有,有没有办法做出这样的路由定义?

【问题讨论】:

    标签: .net owin asp.net-web-api-routing


    【解决方案1】:

    如果您在 OWIN 上运行,则无需接触 Web API 路由即可执行此操作。您应该可以为此使用 Microsoft.Owin.StaticFiles 中间件。示例Setup类:

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var webApiConfig = new HttpConfiguration();
    
            // Your Web API routing setup here...
    
            app.UseWebApi(config);
    
            var assemblyPath = Assembly.GetExecutingAssembly().Location;
            var assemblyFolder = Path.GetDirectoryName(assemblyPath);
            var staticFolder = Path.Combine(exeFolder, "Static");
    
            app.UseStaticFiles(webFolder);
        }
    }
    

    这将提供来自<dll folder>\Static 文件夹的静态文件。因此,如果您的应用位于 C:\MyApp,点击 http://localhost/index.html,将作为静态 HTML 提供 C:\MyApp\Static\index.html

    【讨论】:

    • 这对我不起作用,反射获取程序集的临时文件夹。即使我在 app.UseStaticFiles(@"C:\etc") 中硬编码绝对路径,它也不起作用。 “UseStaticFiles”的第一个参数应该是RequestPath(不能以“/”结尾),而不是物理路径。我正在使用 Owin.StaticFiles v2.1.0。
    • 在 VS 中设置静态内容文件,使其复制到程序集目录。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 2013-04-01
    相关资源
    最近更新 更多