C#根据返回的结果和API显示文本

时间:2014-07-23 14:16:32

标签: c# api

我有一个ping请求和API,如果成功则返回“ok”,否则返回失败。我需要帮助更改ping结果的代码,以显示其他文本,例如“你的ping成功”,如果有错误显示“你的ping失败”我是新手编程。

public partial class API_Menu_Ping : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string myCADeveloperKey = ConfigurationManager.AppSettings["CADeveloperKey"];
        string myCAPassword = ConfigurationManager.AppSettings["CAPassword"];

        //Create credentials
        ca.api.APICredentials cred = new ca.api.APICredentials();
        cred.DeveloperKey = myCADeveloperKey;
        cred.Password = myCAPassword;

        //Create the Web Service and attach the credentials
        ca.api.AdminService svc = new ca.api.AdminService();
        svc.APICredentialsValue = cred;

        //call the method

        ca.api.APIResultOfString result = svc.Ping() ;

       PingResult.Text = result.ResultData ;

      }
    protected void PingCaApi_Click(object sender, EventArgs e)
    {

    }
}

2 个答案:

答案 0 :(得分:1)

您只是想将文本操作给用户。您只需要if声明:

if(result.ResultData == "ok") //or whatever a 'yes' result is
   PingResult.Text = "Your ping was successful";
else
   PingResult.Text = "Your ping failed";

或者您可以使用三元运算符缩短它:

PingResult.Text = (result.ResultData == "ok") ? "Your ping was successful" : "Your ping failed";

答案 1 :(得分:0)

我不太喜欢将可能崩溃的代码放入Page_Load处理程序中。如果有任何错误,您可能永远不会看到它。

此外,根据您的长定义,这是熟悉var关键字的好地方。

使用它,我会按如下方式编写例程:

public partial class API_Menu_Ping : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void PingCaApi_Click(object sender, EventArgs e)
    {
        PingResult.Text = null;

        //Create credentials
        var cred = new ca.api.APICredentials();
        cred.DeveloperKey = ConfigurationManager.AppSettings["CADeveloperKey"];
        cred.Password = ConfigurationManager.AppSettings["CAPassword"];

        //Create the Web Service and attach the credentials
        var svc = new ca.api.AdminService();
        svc.APICredentialsValue = cred;

        //call the method
        var result = svc.Ping();

       PingResult.Text = (result.ResultData == "ok") ? "your ping was successful" : "your ping failed";
    }
}