asp.net-web-api - 在 Web API 中,当一个方法包含可空值类型作为参数时,如何重载 Get

标签 asp.net-web-api visual-studio-2012

更新

我最初的假设是可选参数是问题的原因。这似乎是不正确的。相反,当这些方法之一包含某些参数的可为空值类型(例如 int? )时,多个操作方法似乎是一个问题。

我正在使用 Visual Studio 2012 RC,并且刚刚开始使用 Web API。我遇到了一个问题,并收到错误消息“未在与请求匹配的 Controller ‘Bars’上找到任何操作。”

我有一个 Bars Controller 。它有一个接受可选参数的 Get() 方法。

public IEnumerable<string> Get(string h, string w = "defaultWorld", int? z=null)
{
    if (z != 0)
        return new string[] { h, w, "this is z: " + z.ToString() };
    else
       return new string[] { h, w };
}

因此,我使用以下网址对其进行了测试
  • /api/bars?h=你好
  • /api/bars?h=hello&w=world
  • /api/bars?h=hello&w=world&z=15

  • 它适用于所有三个。

    然后,我去添加另一个 Get() 方法,这次使用单个 id 参数
     public string Get(int id)
     {
         return "value";
     }
    

    我再次测试网址。这次/api/bars?h=hello&w=world 和 api/bars?h=hello 失败了。错误信息是 “在与请求匹配的 Controller 'Bar' 上没有找到任何操作。”

    出于某种原因,这两种方法不能很好地配合使用。如果我删除 Get(int id) , 有用。如果我改变int? z 到字符串 z,然后它就可以工作了(但是它需要转换我的操作方法中的对象!)。

    为什么 Web API 会这样做?这是错误还是设计使然?

    非常感谢。

    最佳答案

    我还没有找到这个问题的真正答案(为什么 Web API 这样做),但我有一个解决方法,允许重载 Get()。诀窍是将参数值包装在一个对象中。

    public class Foo
    {
        public string H { get; set; }
        public string W { get; set; }
        public int? Z { get; set; }
    }
    

    和 Bars Controller 修改为
    public IEnumerable<string> Get([FromUri] Foo foo)
    {
        if (foo.Z.HasValue)
            return new string[] { foo.H, foo.W, "this is z: " + foo.Z.ToString() };
        else
            return new string[] { foo.H, foo.W, "z does not have a value" };
    }
    
    [FromUri]是必要的,因为默认情况下,WebAPI 不使用 URI 参数来形成“复杂”对象。一般的想法是复杂的对象来自<form>操作,而不是 GET 请求。

    我仍然会继续检查为什么 Web API 会以这种方式运行,以及这是否真的是一个错误或预期的行为。

    关于asp.net-web-api - 在 Web API 中,当一个方法包含可空值类型作为参数时,如何重载 Get,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11416418/

    相关文章:

    c# - 将 json post 请求中的多个复杂参数传递给 asp.net WebApi

    c# - 使用 HttpClient 通过 GET 连接到 WebApi 时出现 404 错误

    c# - 无法反序列化当前JSON对象,为什么?

    c# - 添加新记录时外键错误

    c# - TFS 文件 .tfsignore 不工作

    asp.net-web-api - WebAPI 中的 TaskScheduler.UnobservedTaskException 取消了操作

    c# - 使用 ASP.NET Web API 返回 JSON 文件

    c++ - 清除 __m128i 的高位字节

    c# - 如何使用 C# 在 Excel 图表中添加虚线网格?

    javascript - 如何显示从数据库中检索到的多行文本