在Web API中没有从C#的HttpPost中找到404

时间:2015-11-06 19:45:21

标签: c# asp.net-web-api .net-4.5.2

当我尝试调用HasAccess时,我收到404:找不到错误。我使用HttpPost来传递User类,因为它在某些字符串中包含/和\符号。这可以作为一个get但由于额外的斜线而无法正常工作,所以我需要弄清楚如何使它作为一个帖子工作或找到围绕\和/限制的另一种方式。这是响应消息:

{Method: POST, RequestUri: 'http://localhost/WebServices/Security/api/SecurityCheck/HasAccess/',
Version: 1.1,
Content: System.Net.Http.ObjectContent`1[[Authorization.Models.User, Authorization, Version=1.0.3.0, Culture=neutral, PublicKeyToken=null]],
Headers:
{
  Accept: application/json
  Content-Type: application/json; charset=utf-8
  Content-Length: 118
}}

以下是Web API中的函数声明

[Route("api/SecurityCheck/HasAccess/")]
[HttpPost]
public bool HasAccess(User current)
{
  if (ValidateUser(current))
  {
    CurrentUser = current;

    return AzMan.Roles.Count != 0;
  }
  return false;
}

Global.asax中的我的路线配置

  GlobalConfiguration.Configure(config =>
  {
    config.MapHttpAttributeRoutes();

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

我从C#调用Web API函数:

public async Task executeAsyncPost(string method, int? operationID = null)
{
  try
  {
    using (var client = new HttpClient())
    {
      client.BaseAddress = new Uri(ConfigurationSettings.AppSettings["SecurityCheckAPI"]);
      client.DefaultRequestHeaders.Accept.Clear();
      client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

      var user = new User();
      user.UserName = User;
      user.Application = Application;
      user.AuthorizationStore = AuthorizationStore;

      string message = "api/SecurityCheck/" + method + "/";
      if (operationID.HasValue)
      {
        message += operationID.Value.ToString() + "/";
      }

      HttpResponseMessage response = await client.PostAsJsonAsync(message, user);

      if(response.IsSuccessStatusCode)
      {
        switch(method)
        {
          case "GetOperationIds":
            _operationIds = await response.Content.ReadAsAsync<int[]>();
            break;
          case "GetOperationNames":
            _operationNames = await response.Content.ReadAsAsync<string[]>();
            break;
          case "CheckAccess":
            _checkAccess = await response.Content.ReadAsAsync<bool>();
            break;
          case "HasAccess":
            _hasAccess = await response.Content.ReadAsAsync<bool>();
            break;
          case "GetRoles":
            _roles = await response.Content.ReadAsAsync<object[]>();
            break;
        }
      }
    }
  }
  catch (Exception ex)
  {
    throw ex;
  }
}

2 个答案:

答案 0 :(得分:0)

删除[Route("api/SecurityCheck/HasAccess/")]上的最终/以及RequestUri本身。

答案 1 :(得分:0)

请求Uri结束时缺少一个/。缺少/实际上从路径中删除了整个授权部分并直接进入api。