【问题标题】:How to trigger debugging with Web Api如何使用 Web Api 触发调试
【发布时间】:2015-09-05 12:34:09
【问题描述】:

是否可以导航到存在 Web api 的 URL?我的努力表明不,常识说它应该是。因此,我想我在其他地方有错误。

我已经启动了 VS 2015,添加了一个新项目 (ASP.NET) 并选择了 web api。我已经创建了我的 api

public class DefaultController : ApiController
{
    public void Index()
    {
        //logic with break points set
    }
}

我还创建了一个“普通”MVC 控制器,因此,当我启动项目时,我的网络浏览器会显示我的 Home 控制器中的索引文件。

现在,我想导航到我的 web api 的关联 URL 我的主控制器(索引视图)的 URL 是

http://localhost:61895/

因此我的 api 应该是(我认为)

http://localhost:61895/api/default/

但我在浏览器中看到以下内容

HTTP 404。您要查找的资源(或其依赖项之一)可能已被删除、名称已更改或暂时不可用。请查看以下 URL 并确保其拼写正确。

而我的 WebApiConfig 是

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

编辑

我也试过localhost:61895/api/Default/Index,但同样的问题

如何在 Visual Studio 中调试我的 API

【问题讨论】:

标签: asp.net-mvc asp.net-web-api2


【解决方案1】:

Web Api 在路由上的工作方式与 Mvc Controller 不同。

web api 中没有 action 部分。

http 动作必须匹配动作的开始或属性。例如:

public class DefaultController : ApiController
{
    public void GetIndex()
    {
        //logic with break points set
    }
}

public class DefaultController : ApiController
{
    [HttpGet]
    public void Index()
    {
        //logic with break points set
    }
}

网址将是

localhost:61895/api/默认

asp.net 上有一个很好的例子:

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

编辑

添加一些屏幕截图。 我创建了一个新的 web api 项目,并创建了新的控制器默认值:

public class DefaultController : ApiController
{
    public void GetIndex()
    {
        var a = "a";
    }
}

然后是我的网址:

http://localhost:4349/api/default

你可以看到断点被击中。

根据 cmets 中的讨论,问题是 Global.asax.cs 文件

顺序很重要,必须按照以下顺序

 public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

GlobalConfiguration.Configure(WebApiConfig.Register);

必须在

之前

RouteConfig.RegisterRoutes(RouteTable.Routes);

【讨论】:

  • 那么,如何在 Visual Studio 中调试代码? +1,因为这很清楚:)
  • @MyDaftQuestions 将断点放在 GetIndex() 方法的请求处(就像您在任何其他应用程序中所做的那样),并在调试模式下运行 VS。然后导航到 url,然后它应该在断点处停止
  • 我添加了额外的 GetIndex 并将 [HttpGet] 添加到我原来的 Index 方法中 - 然后我导航到 localhost:61895/api/Default - 它没有帮助
  • @MyDaftQuestions 你不需要两者。只是一个带有 [HttpGet] 或一个名为 GetIndex
  • 我尝试使用 [HttpGet] 和我的原始索引,然后我删除了它并仅尝试使用 GetIndex(并且没有属性)。同样的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-28
相关资源
最近更新 更多