如何将所有路由传递给 Web API 中的单个控制器?

Zac*_*ith 3 c# asp.net-web-api asp.net-web-api-routing

我有一个 OWIN 托管的应用程序,它可以做两件事:

  1. 提供 API 位于 mydomain.com/api/...

  2. 将所有其他请求路由到返回 HTML 页面的单个控制器

我目前有这条路线:

config.Routes.MapHttpRoute(
    name: "default",
    routeTemplate: "{controller}",
    defaults: new { controller = "Index" }
);
Run Code Online (Sandbox Code Playgroud)

而这个控制器:

public class IndexController : ApiController
{
    public HttpResponseMessage Get()
    {
        string html = File.ReadAllText(@"C:/www/.../index.html");
        HttpResponseMessage response = new HttpResponseMessage
        {
            Content = new StringContent(html),
            StatusCode = System.Net.HttpStatusCode.OK
        };
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
        return response;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我去我的家乡路线时,这很好用:

mydomain.com => HTML
Run Code Online (Sandbox Code Playgroud)

如何配置路由模板,以便始终访问同一个控制器?

mydomain.com/path1 => I want the same HTML
mydomain.com/path1/something => I want the same HTML
mydomain.com/path2 => I want the same HTML
mydomain.com/path3/somethingElse => I want the same HTML
etc
Run Code Online (Sandbox Code Playgroud)

我想要的看起来很简单……我不在乎它是 GET、POST 还是什么。除非路线以api/我想返回单个 HTML 页面开头。

是否有使用 Web API 实现此目的的好方法?

=== 编辑

我也在使用静态文件 - 所以应该明确忽略静态文件系统的路径:

HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.IgnoreRoute("StaticFiles", "Public/{*url}");
...
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 5

创建单独的路由。一个用于API所有其他路径,一个捕获所有路径

//mydomain.com/api/...
config.Routes.MapHttpRoute(
    name: "api",
    routeTemplate: "api/{controller}",
    defaults: new { controller = "Service" }
);


//mydomain.com/path1 => I want the same HTML
//mydomain.com/path1/something => I want the same HTML
//mydomain.com/path2 => I want the same HTML
//mydomain.com/path3/somethingElse => I want the same HTML
config.Routes.MapHttpRoute(
    name: "default-catch-all",
    routeTemplate: "{*url}",
    defaults: new { controller = "Index", action = "Handle" }
);
Run Code Online (Sandbox Code Playgroud)

控制器可以根据需要处理请求。

public class IndexController : ApiController {
    [HttpGet]
    [HttpPost]
    [HttpPut]
    public IHttpActionResult Handle(string url) {
        string html = File.ReadAllText(@"C:/www/.../index.html");
        var response = Request.CreateResponse(System.Net.HttpStatusCode.OK, html, "text/html");
        return ResponseMessage(response);
    }
}
Run Code Online (Sandbox Code Playgroud)