我有一个OWIN托管的应用程序可以完成两件事:
在mydomain.com/api/...
将所有其他请求路由到返回HTML页面的单个控制器
我目前有这条路线:
config.Routes.MapHttpRoute(
name: "default",
routeTemplate: "{controller}",
defaults: new { controller = "Index" }
);
这个控制器:
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
如何配置路由模板以便始终转到同一个控制器?
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}");
...
答案 0 :(得分:1)
创建单独的路线。一个用于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" }
);
控制器可以根据需要处理请求。
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);
}
}