c# - 如何将所有路由传递给 Web API 中的单个 Controller ?

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

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

  1. mydomain.com/api/...

    提供 API
  2. 将所有其他请求路由到返回 HTML 页面的单个 Controller

我目前有这条路线:

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

还有这个 Controller :

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;
    }
}

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

mydomain.com => HTML

如何配置路由模板,以便始终转到同一个 Controller ?

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

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

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

=== 编辑

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

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

最佳答案

创建单独的路线。一个用于 API 和一个用于所有其他路径的 catch all route

//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" }
);

Controller 可以根据需要处理请求。

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);
    }
}

关于c# - 如何将所有路由传递给 Web API 中的单个 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49431621/

相关文章:

c# - 使用媒体类型对 ASP.NET Web API 2 进行版本控制

c# - 运行 WebAPI 的路径

c# - 使用 WebClient 下载显示进度

c# - 生成图像后打印图像 [c#]

c# - 人们如何在 Web API 中测试他们的 [RequireHttps] 属性?

.net - Postman 客户端凭据流与 Azure AD 保护资源

java - Java 和 C# 中使用 Bouncy CaSTLe 进行 RSA 加密的结果之间的差异

c# - 尝试更改 ASP.NET Identity 2.0 中的表名

jQuery 2.0 + ASP.NET WebApi POST 空响应 = 失败

c# - OData v4 路由前缀?