【问题标题】:Http,Get with a string parameter returns http 404Http,Get带字符串参数返回http 404
【发布时间】:2014-10-13 23:13:50
【问题描述】:

我正在尝试通过将单个字符串作为参数传递来执行 http.Get 请求。

到目前为止我尝试过的角码是,

1)

 var abseURL = 'http://localhost:17493/api/UsersApi/GetUsersByEmail/';
 var email ='testemail@domain.com';
 $http.get(abseURL + email).then(OnComplete, OnError);
  • 返回 http 404 错误

2)

$http({
        url: abseURL,
        method: "GET",
        params: { email: 'testemail@domain.com'}
    }).then(OnComplete,OnError);
  • 上述http.get请求返回Http 500错误

我的 webApi 控制器方法定义为,

        [ActionName("GetUsersByEmail")]
        [CamelCasedApiControllerAttribute]
        public async Task<IHttpActionResult> GetUsersByEmail(string email)
        {
            Users users = await db.Users.FindAsync(email);
            if (users == null)
            {
                return NotFound();
            }
            return Ok(users);
        }

此外,在我的 Global.asax.cs 文件中,我已将路线映射如下

 protected void Application_Start(object sender, EventArgs e)
        {
            GlobalConfiguration.Configure(config =>
            {              
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );

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

            });

        }

如果我传递一个 Int 参数,它会在我的 WebApiController 中找到正确的操作 但是当我使用字符串参数更改调用时,它无法找到正确的操作方法。

【问题讨论】:

    标签: angularjs asp.net-web-api2


    【解决方案1】:

    您可以将 email 参数重命名为 id:

    public async Task<IHttpActionResult> GetUsersByEmail(string id)
    {
        Users users = await db.Users.FindAsync(id);
        if (users == null)
        {
            return NotFound();
        }
        return Ok(users);
    }
    

    【讨论】:

    • 是的,只要我将 Get 调用设为 $http.get(abseURL + id).then(OnComplete, OnError); * id 是一个字符串,这确实有效。如果我包装参数并按如下方式发出 Get 请求,它将返回 Http 500 错误。 $http({ url: abseURL, method: "GET", params: { email: 'testemail@domain.com'} }).then(OnComplete,OnError);
    • @AJ17 - 我知道这是旧的,但也许它会帮助其他人。使用params 失败的原因是你没有重命名参数 - 你仍然使用email。如果您将参数重命名为 id 它会起作用:$http({ url: abseURL, method: "GET", params: { id: 'testemail@domain.com'} }).then(OnComplete,OnError);
    【解决方案2】:

    在我看来,路由未设置为处理此问题。您可以尝试改用以下方法:

    var abseURL = 'http://localhost:17493/api/UsersApi/GetUsersByEmail/?email=';
    var email ='testemail@domain.com';
    $http.get(abseURL + email).then(OnComplete, OnError);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      相关资源
      最近更新 更多