0

我想使用带有 JSON 的 C# 创建一个 .NET Web 服务。但是我的 web 服务的返回语句中有错误,cannot implicitly convert type 'string' to 'Model.User' 如何解决该错误行?

这是我的 WebService.asmx :

[OperationContract]
    public Model.User GetUser(string ccduser)
    {
        Model.User user = new Model.User();
        string connectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
        using (SqlConnection connection = new SqlConnection(connectionString)) {
            string sql = "Select * from ms_webuser where ccduser = '" + ccduser + "'";
            connection.Open();

            SqlCommand command = new SqlCommand(sql, connection);
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                user.cnmuser = reader["cnmuser"].ToString();
            }
        }

        MemoryStream stream = new MemoryStream();
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Model.User));
        serializer.WriteObject(stream, user);
        stream.Position = 0;
        StreamReader streamReader = new StreamReader(stream);
        return streamReader.ReadToEnd(); //here is the error red line
    }

这是我的 Model.User 类:

namespace Model
{
    public class User
    {
        private string _ccduser;
        private string _cnmuser;

        public string ccduser
        {
            get { return _ccduser; }
            set { _ccduser = value; }
        }

        public string cnmuser
        {
            get { return _cnmuser; }
            set { _cnmuser = value; }
        }

    }
}
4

1 回答 1

1

您收到该错误是因为该ReadToEnd方法返回一个字符串,并且您已声明您的方法返回一个Model.User

要解决它,您应该返回要返回的用户,或者您应该更改方法以返回字符串。

于 2012-06-21T02:29:30.410 回答