c#根据从API返回的结果显示文本

本文关键字:结果 显示 文本 返回 API | 更新日期: 2023-09-27 18:14:37

我有一个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)
    {
    }
}

c#根据从API返回的结果显示文本

你只是想操作文本给用户。您只需要一个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";

我真的不喜欢把可能崩溃的代码放入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";
    }
}