【问题标题】:New WebApi Project doesn't have default routing for API (but still works)新的 WebApi 项目没有 API 的默认路由(但仍然有效)
【发布时间】:2013-03-04 20:32:24
【问题描述】:

我创建了一个新的 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 的路由在哪里?

干杯

戴夫

【问题讨论】:

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


    【解决方案1】:

    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

    【讨论】:

    • 我没有看到你实际上写了它在哪个类,否则我会尽快将其标记为正确。感谢您的回答!
    【解决方案2】:

    它生活在不同的类中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-29
      • 2019-05-08
      • 2011-05-12
      • 1970-01-01
      • 2015-06-21
      • 2017-01-19
      • 2018-12-18
      • 2020-04-15
      相关资源
      最近更新 更多