【问题标题】:web service return anonymous object from methodWeb服务从方法返回匿名对象
【发布时间】:2012-06-04 18:36:44
【问题描述】:

我有一个简单的 Web 服务,它从数据库中获取数据,我想将这些数据作为数据集、字符串、XML 返回。但是 Web 服务 xml 没有得到我返回的类型。问题是,是否可以作为对象和 Web 服务 XML 返回以显示正确的标签。目前它显示这个标签 anytype 而不是 string 例如。

方法如下

 [WebMethod]
public Object serviceForPostcode(String postCode, String type)
{
/**
* 
*  create dataset to store query
*  convert dataset to required return type
*  create types for returned object
*  
* 
**/

    SqlDataAdapter adapter = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand();
    SqlConnection conn = new SqlConnection(dbConnection());
/**
* 
*              -- types--
* 
**/
    XmlDocument xmlD = new XmlDocument();
    StringWriter sw = new StringWriter();
    DataSet dataSet = new DataSet();
/**
* 
* 
**/ 

    // connection and query string
    string dbQuery = "SELECT id, address1, address2, address3, address4, address5, post_code, country FROM paf WHERE (post_code = @postCode)";
    try
    {
        cmd.Parameters.Add(new SqlParameter("@postcode",SqlDbType.NChar, 10)).Value = postCode.ToUpper();
        cmd.CommandText = (dbQuery);
        cmd.CommandType = CommandType.Text;
        cmd.Connection = conn;
        adapter.SelectCommand = cmd;
        adapter.Fill(dataSet,"post codes");

    }
    catch(Exception e)
    {
        System.Web.HttpContext.Current.Response.Write(e.Message);

    }
    finally
    {
       //close database connection
        conn.Close();
    }
    if (type.Equals("xml", StringComparison.InvariantCultureIgnoreCase))
    {
        return dataSet.GetXml();
    }
    else if (type.Equals("string", StringComparison.InvariantCultureIgnoreCase))
    {

        dataSet.WriteXml(sw);
        return sw.ToString(); 
    }
    else if(type.Equals("dataset",StringComparison.InvariantCultureIgnoreCase))
    {
        return "";
    }

        return "error";
}

【问题讨论】:

  • 所以你想要一种可以返回 3 种不同类型的方法?

标签: c# web-services service


【解决方案1】:

为什么不创建三种不同的方法?

public string serviceForPostcodeString(String postCode)

public XElement serviceForPostcodeXML(String postCode)

public DataSet serviceForPostcodeDataSet(String postCode)

或者总是返回一个 DataSet 并让消费者将其转换为 XML 或 String。

编辑

一个技巧是使用泛型类型,但这不适用于 Web 服务。但是您也可以在客户端使用通用方法来包装对 Web 服务的调用。像这样的:

public T serviceForPostcodeWrapped<T>(String postCode)
{
    // ... do some checking for allowed types here ...
    return (T)serviceForPostcode(postCode, typeof(T).Name);
}

免责声明:我说你可以,而不是你应该

【讨论】:

  • 是的,我可以,我只是想可能有办法让这项工作
【解决方案2】:

试试这个:

 [WebMethod]
public string serviceForPostcode(String postCode, String type)

【讨论】:

  • 那么所有对象都是字符串类型。我可能会返回 xmldocument,这样就行不通了。
猜你喜欢
  • 1970-01-01
  • 2014-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多