新的WebApi项目没有API的默认路由(但仍然有效)

时间:2013-03-16 00:15:35

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

我已经创建了一个新的WebAPI MVC项目,API控制器的路径为http://localhost:1234/api,它们可以在此路由中工作,但RegisterRoutes类不包含默认路由,它包含以下内容:

public static void RegisterRoutes(RouteCollection routes)
{
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
     routes.MapRoute(
         name: "Default",
         url: "{controller}/{action}/{id}",
         defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

API的路由在哪里?

干杯

戴夫

2 个答案:

答案 0 :(得分:4)

Visual Studio项目模板创建一个默认路由,如下所示:

routes.MapHttpRoute(
   name: "API Default",
   routeTemplate: "api/{controller}/{id}",
   defaults: new { id = RouteParameter.Optional }
);

您可以在WebApiConfig.cs目录中找到App_Start文件中找到此内容

http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

答案 1 :(得分:1)

它生活在一个不同的阶层:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace HelloWorldApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
            // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
            // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
            //config.EnableQuerySupport();

            // To disable tracing in your application, please comment out or remove the following line of code
            // For more information, refer to: http://www.asp.net/web-api
            config.EnableSystemDiagnosticsTracing();
        }
    }
}