代码之家  ›  专栏  ›  技术社区  ›  developer9969

在webapi控制器中调用方法。在uri中传递字符串的net core无效

  •  0
  • developer9969  · 技术社区  · 7 年前

    我试图从测试中调用WebAPicController(.net core)中的方法

    如果我的请求对象的Id为string,则它不起作用,而int则起作用

    在我的noddy示例中,我做错了什么?

        [Fact]
        public async Task WhyDoesNotWorkWithIdAsString()
        {
            string thisQueryDoesNotWork = "http://localhost:1111/api/v1/shop/customers?id=1";
            string thisQueryWorksProvidedTheIdIsAnInt = "http://localhost:1111/api/v1/shop/customers/1";
            var response = await client.GetAsync(thisQueryDoesNotWork);
            var response2 = await client.GetAsync(thisQueryWorksProvidedTheIdIsAnInt);
    
            //omitted asserts
        }
    
    
    [Route("api/[controller]")]
    public class ShopController: Controller
    {
    
        [HttpGet]
        [Route("{id}",Name ="GetCustomerAsync")]
        [ProducesResponseType(typeof(GetCustomerResponse), (int)HttpStatusCode.OK)]
                //more ProducesResponseType omitted
        public async Task<IActionResult> GetCustomerAsync([FromQuery]GetCustomerRequest request)
        {
            //code omitted
        }
    }
    
    
    public class GetCustomerRequest
    {
        Required]
        public string Id { get; set; }
        // public int Id { get; set; }   //works with int but not with a string
    
    }
    

    }

    也低于正确值

    [FromQuery]=仅使用Get [来自正文]=使用Put Post

    是否有链接解释何时使用此参数绑定?

    非常感谢

    2 回复  |  直到 7 年前
        1
  •  1
  •   Nkosi    7 年前

    在里面

    [Route("{id}",Name ="GetCustomerAsync")]
    

    {id} 模板参数是路由的一部分,但在操作参数中,是否通过 [FromQuery] ,这就是它不匹配的原因。

    它正在期待

    http://localhost:1111/api/v1/shop/customers/1
    

    但你正在发送

    http://localhost:1111/api/v1/shop/customers?id=1
    

    这就是为什么第二个链接有效,而第一个链接无效。

    参考 Routing to Controller Actions

    至于对 [From*] 属性

    [FromHeader] ,则, [来自查询] ,则, [FromRoute] ,则, [FromForm] :使用这些指定要应用的确切绑定源。
    。。。
    [FromBody] :使用配置的格式化程序绑定请求正文中的数据。格式化程序是根据请求的内容类型选择的。

    参考 Model Binding in ASP.NET Core

        2
  •  0
  •   developer9969    7 年前

    我已经发现了问题所在,httpget或路由的名称必须与您在链接中设置的名称匹配