[英]c#: Asp.net WebApi default route to index.html
I am trying to create an Asp.net WebApi / Single Page Application. 我正在尝试创建一个Asp.net WebApi /单页面应用程序。 I would like my server to dispense index.html if no route is given.
如果没有给出路由,我希望我的服务器分配index.html。 I would like it to use a controller when one is specified in the normal "{controller}/{id}" fashion.
我希望它以正常的“{controller} / {id}”方式指定一个控制器。
I realized that I can visit my index page by using http://localhost:555/index.html . 我意识到我可以使用http:// localhost:555 / index.html访问我的索引页面。 How do I do the same by visiting http://localhost:555 ?
我如何通过访问http:// localhost:555来做同样的事情?
Just add a route to your WebApiConfig file for index page. 只需为您的WebApiConfig文件添加一个路径以获取索引页面。 Your method should look like this:
您的方法应如下所示:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Attribute routing
config.MapHttpAttributeRoutes();
// Route to index.html
config.Routes.MapHttpRoute(
name: "Index",
routeTemplate: "{id}.html",
defaults: new {id = "index"});
// Default route
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
The solution was to create an empty DefaultRoute . 解决方案是创建一个空的DefaultRoute 。
// I think this passes control through before trying to use a Controller
routes.MapHttpRoute(
"DefaultRoute", "");
routes.MapHttpRoute(
"DefaultAPI",
"{controller}/{id}",
new { Controller = "Home", Id = RouteParameter.Optional });
Another solution was to prefix my WebApi with 'api', which is not entirely what I wanted, but is a suitable solution. 另一个解决方案是在我的WebApi前加上'api',这不完全是我想要的,但它是一个合适的解决方案。 This was shown in Herman Guzman's answer, but is not his answer.
Herman Guzman的回答显示了这一点,但不是他的回答。
// Default route
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.