1

我已经使用 C# 和 MySQL 在 asp.net 中创建了 webservice。我想从此服务返回多个值。我正在使用以下代码:

[WebMethod]
public string RegisterUserViaFacebook(string fbid, string fbmailid,string devicetype)  
{
    string success = "Already Registered";
    string id="", name="";

    if (!ExistsFBID(fbid))
    {
        name = GenerateUserName();

        string password = generatePassword(10);

        string insertUser = "Insert into tbl_userinfo(UserName,Password,Facebook_ID,Facebook_EmailID,DeviceType) values";
        insertUser += "( '" + name + "' ,'" + password + "','" + fbid + "','" + fbmailid + "','" + devicetype + "' )";
        con = new MySqlConnection(conString);
        con.Open();
        MySqlCommand cmd = new MySqlCommand(insertUser, con);
        success = cmd.ExecuteNonQuery().ToString();
        con.Close();

        string getID = "SELECT UserID from tbl_userinfo where UserName='" + name + "'  ";
        con = new MySqlConnection(conString);
        con.Open();
        MySqlCommand cmd1 = new MySqlCommand(getID, con);
        id = cmd1.ExecuteScalar().ToString();
        con.Close();


        if (Convert.ToInt16(success) > 0)
        {
            SendMail(fbmailid, name, password);
            success = "New User"  ;
        }
        else
            success = "Error in Insertion";
    }
    else
    {
        string getID1 = "SELECT UserID, UserName from tbl_userinfo where Facebook_ID='" + fbid + "' ";
        con = new MySqlConnection(conString);
        con.Open();
        MySqlCommand cmd2 = new MySqlCommand(getID1, con);
        MySqlDataReader info = cmd2.ExecuteReader();

        while (info.Read())
        {
            id = info.GetString(0);
            name = info.GetString(1);

        }
        con.Close();
    }

    string jsonString = JsonConvert.SerializeObject(success);
    String finalString = "{\"USER IS\":";
    finalString += jsonString;
    finalString += "}";

    string jsonString1 = JsonConvert.SerializeObject(id);
    String finalString1 =finalString + "{\"ID IS\":";
    finalString1 += jsonString1;
    finalString1 += "}" ;

    string jsonString2 = JsonConvert.SerializeObject(name);
    String finalString2 = finalString1 + "{\"NAME IS\":";
    finalString2 += jsonString2;
    finalString2 += "}";
    return finalString2;


 }

但它返回单个字符串中的所有值。我想将值单独返回为Succeess,IDName.

我怎样才能做到这一点?

4

2 回答 2

8

创建一个简单的类来保存成功、id 和名称并返回它的序列化实例。

public class RegistrationResult
{
   public string Success { get; set; }
   public string Name { get; set; }
   public int Id { get; set; }
}

你可以这样做:

var result = new RegistrationResult { Success = success, Name = name, Id = id} ;
return JsonConvert.SerializeObject(success);
于 2012-05-30T09:57:01.583 回答
0

您可能希望在 JSON 中返回单个对象。

return "{user: "+JsonConvert.SerializeObject(success)+", id: "+JsonConvert.SerializeObject(id)+", name: "+JsonConvert.SerializeObject(name)+"}";

Oded的回答也很好。它更清楚一点,但还需要一个额外的类。

于 2012-05-30T10:04:04.287 回答