【问题标题】:WebApi 2 GET has special character in parameterWebApi 2 GET 在参数中有特殊字符
【发布时间】:2016-04-06 13:05:38
【问题描述】:

当我使用具有 special char 的字符串参数调用 webapi2 GET 时,我的问题出现了(正常字符都可以正常工作)。

AngularJs

this.getByContactValue = function (contactValue) {   
        return $http.get("/api/subjects/"+ contactValue+ "/ContactValue" );
    }

c#

[Route("api/subjects/{contactValue}/ContactValue")]
public IEnumerable<Subject> GetByContactValue(string contactValue)
{
    return repository.GetByContactValue(contactValue);
}

响应是 404 错误。 我也试过用这种方式修改请求

this.getByContactValue = function (contactValue) {
        var request = $http({
            method: "get",
            url: "/api/subjects/ContactValue", //modified the route in c# controller
            data: contactValue
        });
        return request;
    }

但错误是一样的。

调用 webapi 的最佳方式是什么?

【问题讨论】:

标签: c# angularjs asp.net-web-api asp.net-web-api2


【解决方案1】:

您必须将查询字符串中的数据传递为

$http({
    url: "/api/subjects/ContactValue", 
    method: "GET",
    params: {contactValue: contactValue}
 });

更新您的操作

[Route("api/subjects/ContactValue?contactValue={contactValue}")]
public IEnumerable<Subject> GetByContactValue(string contactValue)
{
    return repository.GetByContactValue(contactValue);
}

【讨论】:

  • 这样我收到这个错误-The route template cannot start with a '/' or '~' character and it cannot contain a '?' character.我必须在控制器中指定参数的值吗?
【解决方案2】:

我终于这样解决了

[Route("api/subjects/ContactValue")]
public IEnumerable<Subject> GetByContactValue([FromUri]string contactValue)
{                                 
    return repository.GetByContactValue(contactValue);
}

【讨论】:

    【解决方案3】:

    最简单的方法是使用encodeURI或encodeURIComponent,它会在url中编码数据。

    Ts-

       let bg= encodeURIComponent(contactValue);
       return AuthAxios.get(`${APINAME}?bg=${bg}`);
    

    API

        [HttpGet(nameof(GetBgList))]
        public async Task<IActionResult> GetBgList(string bg)
        {
            return Ok(MessageAlert.DataFound(await _bgService.GetBgList(bg)));
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-24
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多