【问题标题】:Enum in URI Template?URI模板中的枚举?
【发布时间】:2013-08-15 17:43:38
【问题描述】:

我正在使用带有路由表的 WCF Restful 服务。

我正在尝试使用枚举来控制输出的序列化方式,但我遇到了麻烦。例如,我有以下枚举:

public enum outputType
{
    JSON, XML, XML_XSD, CSV, TXT
}

然后我尝试使用一个简单的测试调用。

[WebGet(UriTemplate = "{ot}/test")]
public Stream test(outputType ot)
{
   using (DataTable dt = new DataTable("test"))
   {
      //build dummy datatable
      dt.Columns.Add("col1");
      dt.Rows.Add(dt.NewRow());
      dt.Rows[0]["col1"] = "asdf";

      //serialize results
      //takes a datatable and serializes it into the outputType's file format
      return _m.serialize(ot, dt);
   }
}

编译得很好,但给了我错误“UriTemplate 路径段的变量必须具有类型'字符串'。”。

我知道我可以将 ot 变量更改为类型字符串并一起破解一些验证,但我宁愿正确使用框架。我该怎么做?

我担心如果我必须拼凑我自己的解决方案,我将不得不向我的每个 Web 服务入口点添加一个验证功能,这会相当混乱。

【问题讨论】:

  • Serialize 方法采用什么类型的参数?
  • 更改了初始问题以反映对 cme​​ts 的响应。对于这个例子,serialize 只接受一个数据表并将其输出为 outputType 枚举指定的格式

标签: c# .net wcf rest


【解决方案1】:

将参数类型更改为string并转换为Enum

public Stream test(string ot) {
    ot = ot ?? "XML";

    try {
        OutputType kind = Enum.Parse(typeof(OutputType), ot);
        . . . 
    }catch(ArgumentException e) }
       . . .
    }
}

【讨论】:

    【解决方案2】:

    这不是一个很好的解决方案,但您可以这样做:

    [WebGet(UriTemplate = "json/test")]
    public Stream testJSON()
    {
        return test(outputType.JSON);
    }
    
    [WebGet(UriTemplate = "xml/test")]
    public Stream testXML()
    {
        return test(outputType.XML);
    }
    
    ...
    
    private Stream test(outputType ot)
    {
       using (DataTable dt = new DataTable("test"))
       {
          //build dummy datatable
          dt.Columns.Add("col1");
          dt.Rows.Add(dt.NewRow());
          dt.Rows[0]["col1"] = "asdf";
    
          //serialize results
          return _m.serialize(outputType, dt);
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多