我有一个 OWIN 托管的应用程序可以做两件事:
在
提供 APImydomain.com/api/...
将所有其他请求路由到返回 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/