繁体   English   中英

c#:Asp.net WebApi到index.html的默认路由

[英]c#: Asp.net WebApi default route to index.html

我正在尝试创建一个Asp.net WebApi /单页面应用程序。 如果没有给出路由,我希望我的服务器分配index.html。 我希望它以正常的“{controller} / {id}”方式指定一个控制器。

我意识到我可以使用http:// localhost:555 / index.html访问我的索引页面。 我如何通过访问http:// localhost:555来做同样的事情?

只需为您的WebApiConfig文件添加一个路径以获取索引页面。 您的方法应如下所示:

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

解决方案是创建一个空的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 });

另一个解决方案是在我的WebApi前加上'api',这不完全是我想要的,但它是一个合适的解决方案。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM