0

我有以下操作方法来执行 API 调用:-

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Rack rack, FormCollection formValues)
        {
            if (ModelState.IsValid) {

                using (var client = new WebClient())
                {
                    var query = HttpUtility.ParseQueryString(string.Empty);
                    foreach (string key in formValues)
                    {
                    query[key] = this.Request.Form[key];
                    }
                    query["username"] = "testuser";
                    query["password"] = ///.....
                    query["assetType"] = "Rack";
                    query["operation"] = "AddAsset";
                    var url = new UriBuilder("http://win-spdev:8400/servlets/AssetServlet");
                    url.Query = query.ToString();
                    try
                    {
                        string xml = client.DownloadString(url.ToString());
                    }

API 调用的返回 XML 如下所示:-

<operation>
<operationstatus>Failure</operationstatus>
<message>Rack already exists.Unable to add</message>
</operation>

但是我如何才能到达消息和操作状态并根据它们显示适当的消息。我用来序列化返回的 Json,例如,但我不知道如何为 XML 执行此操作:-

var serializer = new JavaScriptSerializer();
                    var myObject = serializer.Deserialize<newprocess>(json);
                    string activityid = myObject.activityId;
4

2 回答 2

1

只需将其加载到XmlDocument.

未经测试,从我的脑海中浮现:

    var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(theXML);
    var status = xmlDoc.SelectSingleNode("/operation/operationstatus").InnerText;
    var message = xmlDoc.SelectSingleNode("/operation/message").InnerText;
于 2013-07-31T16:07:51.057 回答
1

如果你使用 ASP.NET mvc,我相信你可以使用 HttpClient,而不是 WebClient:

定义结果类:

   public class operation
   {
          public string operationstatus{get;set;}
          public string message{get;set;}              
   }

然后用它进行自动反序列化:

   var client = new HttpClient();
   var result = client.PostAsync(url, 
        new FormUrlEncodedContent(new Dictionary<string, string>{
           {"username","testuser"},
           {"assetType","Rack"}}))
       .Result.Content
       .ReadAsAsync<operation>().Result;
于 2013-07-31T16:16:01.953 回答