【问题标题】:Web Api 2 empty string parameter GETWeb Api 2 空字符串参数 GET
【发布时间】:2015-02-22 18:59:20
【问题描述】:

我已将路线设置为: [路线(“{id}/users/search/{search}”)] 相关的动作是: SomeAction(int id, 字符串文本)

该服务具有以下功能。 对于 id={id} 的资源,该资源的用户获取与 {search} 字词(用户名、电子邮件等)匹配的用户。

{search} 可以有值,因此服务只返回匹配的实体,或者没有值(空字符串或 null),因此服务返回所有内容。

对于具有值的部分,它可以正常工作。 对于第二部分,我找不到设置与空字符串匹配的获取请求的内容。

我尝试了以下方法: 1/users/search/null {搜索} = "null" 1/users/search/ 不匹配路由 1/users/search 不匹配路由

有没有人暗示如何做到这一点?

更新:我已尝试替换操作: SomeAction(int id, 字符串文本) 和: SomeAction(Model model) 其中model是

public class ApplicationUserSearchModel
{
    [Required]
    public int Id { get; set; }
    [Required(AllowEmptyStrings = true)]
    public string MatchText { get; set; }
}

没有运气,因为我不知道要发送什么才能将 url 匹配到这个。

【问题讨论】:

    标签: asp.net-web-api routes


    【解决方案1】:

    您应该使用? 标记您的search 参数以在路由中将其标记为可选,并在您的操作中将其默认设置为null

    [Route("{id}/users/search/{search?}")]
    public HttpResponseMessage Search(int id, string search = null)    
    

    我最初认为路由/动作参数名称是问题所在,但我错了。这是以前的答案:

    您的路由定义中的参数名称和您的操作不匹配,这是导致您的问题的原因。

    [Route("{id}/users/search/{search}")]
    public HttpResponseMessage Search(int id, string text)
    

    您应该将操作中的string 参数从text 更新为search,以匹配Route 属性中的参数名称。

    【讨论】:

    • 问题不在于服务本身。效果很好。鉴于上述路线,您如何使用 {search} 绑定到空字符串来调用此服务是个问题!
    • 我会尝试的,但我想我已经没有运气了。我仍然不知道如何调用服务以获得这个结果。任何见解你是如何做到的,因为你的似乎有效?
    • 您应该可以通过调用 GET website/1234/users/search 或 GET website/1234/users/search/firstname%20lastname 访问此路由
    猜你喜欢
    • 2015-02-02
    • 2021-02-24
    • 1970-01-01
    • 2015-04-11
    • 2014-08-06
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多