WebAPI路由 - 将所有请求映射到子文件夹

时间:2015-04-13 20:24:19

标签: c# asp.net asp.net-web-api routing

我尝试做一些非常简单的事情,但我无法在谷歌或文档中找到任何内容。

我有一个空的Web API应用程序,使用默认的WebApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

我添加的唯一内容是带有html / js应用程序的文件夹:

WebApplication
|-- App_Start
|-- Controllers
|-- MySubFolder
|   |-- index.html
|   |-- js
|   |   `-- app.js
|   |-- css
|   |   `-- style.css
`-- Global.asax

我希望每个请求都不以" api /"开头。被重定向到MySubFolder。例如:

  • GET / - > /MySubFolder/index.html
  • GET /js/app.js - > /MySubFolder/js/app.js
  • GET / api / user / - > UserController(已使用默认规则)

1 个答案:

答案 0 :(得分:1)

我用owin解决了它:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var httpConfiguration = new HttpConfiguration();

        // Configure Web API Routes:
        // - Enable Attribute Mapping
        // - Enable Default routes at /api.
        httpConfiguration.MapHttpAttributeRoutes();
        httpConfiguration.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        app.UseWebApi(httpConfiguration);

        // Make ./MySubFolder the default root of the static files in our Web Application.
        app.UseFileServer(new FileServerOptions
        {
            RequestPath = new PathString(string.Empty),
            FileSystem = new PhysicalFileSystem("./MySubFolder"),
            EnableDirectoryBrowsing = true,
        });

        app.UseStageMarker(PipelineStage.MapHandler);
    }
}
相关问题