c# - 你如何调试 MVC 4 API 路由?

标签 c# .net asp.net-mvc rest asp.net-mvc-4

我有一个使用 RESTsharp 与我的 MVC4 RESTful 服务器通信的 WP7 游戏,但我经常在发出有效请求时遇到问题,因此我想在它失败的地方进行调试。

这是一个示例,我的 GameController 上的 Constructor 被命中,但 Post 方法没有被命中,我不明白为什么。

客户端代码:

public void JoinRandomGame()
{
  client = new RestClient
  {
      CookieContainer = new CookieContainer(),
      BaseUrl = "http://localhost:21688/api/",
  };

  client.Authenticator = GetAuth();

  RestRequest request = new RestRequest(Method.POST)
  {
      RequestFormat = DataFormat.Json,
      Resource = "game/"

  };

  client.PostAsync(request, (response, ds) =>
  {});
}

服务器代码:

    public void Post(int id)
    {
        if (ControllerContext.Request.Headers.Authorization == null)
        {
            //No auth
        }
        if (!loginManager.VerifyLogin(ControllerContext.Request.Headers.Authorization.Parameter))
        {
            //Failed login
        }

        string username;
        string password;
        LoginManager.DecodeBase64(ControllerContext.Request.Headers.Authorization.Parameter, out username, out password);
        gameManager.JoinRandomGame(username);
    }

我的路线是这样的

       routes.MapHttpRoute(
            name: "gameAPI",
            routeTemplate: "api/game/{gameId}",
            defaults: new
            {
                controller = "game",
                gameId = RouteParameter.Optional
            }             
        );

最佳答案

另一种方法是在 Global.asax.cs 中添加一个事件处理程序来接收传入的请求,然后在 VS 调试器中查看路由值。按如下方式重写 Init 方法:

public override void Init()
{
    base.Init();
    this.AcquireRequestState += showRouteValues;
}

protected void showRouteValues(object sender, EventArgs e)
{
    var context = HttpContext.Current;
    if (context == null)
        return;
    var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context)); 
}

然后在showRouteValues中设置断点,查看routeData中的内容。

请记住,在 Web API 项目中,Http 路由位于 WebApiConfig.cs 中,而不是 RouteConfig.cs

关于c# - 你如何调试 MVC 4 API 路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11473038/

相关文章:

c# - 自定义配置、ConfigurationElements 和 ConfigurationProperties

asp.net-mvc - MVC Razor 有没有办法通过从 List<string> ViewModel 生成 SelectListItems 来填充 DropdownListFor

c# - 对于 C#,在调用 GetWindowText 等 Win32 函数时使用 'string' 而不是 'StringBuilder' 是否有缺点?

c# - ASP.Net:在 Page_Load 中调用异步方法

c# - LINQ 查询为 Entity DB 中的嵌套对象返回 null

c# - datagridview 文本框列的逗号分隔符

.net - ODBC Oracle 错误

c# - 如果我有 PropertyInfo 和带有此扩展变量的对象,我可以调用扩展方法吗?

c# - Controller 中的 "The entity or complex type cannot be constructed in a LINQ to Entities query"

c# - .Net Core MVC 自定义登录屏幕