ASP.NET Web Api返回对象类型为JSON还是XML

在Umbraco平台上开发过程中,我用WebApi返回JSON result给前端

前端使用React调用这个web api来获取JSON result

我写的web api方法是返回JSON 类型的string, 代码如下

        [HttpGet]
        [HttpQueryStringFilter("queryStrings")]
        public string GetPDFSearchResults(FormDataCollection queryStrings)
        {
            string product = queryStrings.HasKey("product") ? queryStrings.GetValue<string>("product") : "0003";
            string category = queryStrings.HasKey("category") ? queryStrings.GetValue<string>("category") : "0002";
            string docType = queryStrings.HasKey("docType") ? queryStrings.GetValue<string>("docType") : "0001";
            string terms = queryStrings.HasKey("search") ? queryStrings.GetValue<string>("search") : string.Empty;
            var jsonError = JsonHelper.PDFJsonError();
            HttpResponseMessage resp = new HttpResponseMessage();
            resp.Content = new StringContent(jsonError, System.Text.Encoding.UTF8, "application/json");
            if (!string.IsNullOrEmpty(terms))
            {

                var results = Umbraco.PerformContentSearch(terms, product, category, docType);


                //var jsonResult = JsonConvert.SerializeObject(results);
                var jsonResult = "";
                foreach (PDFSearchResult mapResult in results)
                {

                    var docTypeJson = JsonHelper.getJsonByObject(mapResult.DocumentType);
                    docTypeJson = docTypeJson.TrimStart('[').TrimEnd(']');
                    docTypeJson = docTypeJson.Replace(@"\/", "/");
                    var categoryJson = JsonHelper.getJsonByObject(mapResult.Category);
                    categoryJson = categoryJson.TrimStart('[').TrimEnd(']');
                    var productJson = JsonHelper.getJsonByObject(mapResult.Product);
                    productJson = productJson.TrimStart('[').TrimEnd(']');

                    jsonResult += "{\"id\":" + mapResult.Id + ",";
                    jsonResult += "\"approvalStatus\":\"" + mapResult.ApprovalStatus + "\",";
                    jsonResult += "\"score\":\"" + mapResult.Score + "\",";
                    jsonResult += "\"title\":\"" + mapResult.Title + "\",";
                    jsonResult += "\"file_name\":\"" + mapResult.pdfName + "\",";
                    jsonResult += "\"url\":\"" + mapResult.FileUrl + "\",";
                    jsonResult += "\"create_date\":\"" + mapResult.CreateDate + "\",";
                    jsonResult += "\"update_date\":\"" + mapResult.UpdateDate + "\",";


                    jsonResult += JsonHelper.GetConditionJson(docTypeJson, categoryJson, productJson) + "},";
                }

                jsonResult = jsonResult.TrimEnd(',');



                return jsonResult

                //return Json(searchResults, JsonRequestBehavior.AllowGet);

            }
            else
            {
                return "Search term not found"
                //return Json("Search term not found", JsonRequestBehavior.AllowGet);
 
            }




        }

但在Chrome客户端调用这个web api时,发现它返回的是

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
{"company":"Aus 7-11 Mobil Australia","customer":"ECL Group Australia Pty Ltd","dispatch_date":"2015-02-12","has_warranty":false,"serial_number":"1401410","site":"2273 West Ryde","warranty_date":""}
</string>

 或者在IE上返回的是

"{\"company\":\"Aus 7-11 Mobil Australia\",\"customer\":\"ECL Group Australia Pty Ltd\",\"dispatch_date\":\"2015-02-12\",\"has_warranty\":false,\"serial_number\":\"1401410\",\"site\":\"2273 West Ryde\",\"warranty_date\":\"\"}"

而我实际需要的返回结果是

{"company":"Aus 7-11 Mobil Australia","customer":"ECL Group Australia Pty Ltd","dispatch_date":"2015-02-12","has_warranty":false,"serial_number":"1401410","site":"2273 West Ryde","warranty_date":""}

如何解决呢

在读了这篇文章 http://www.luckyonecn.com/blog/fix_content-type_to_Applicationjson_in_WebApi/ 后,

我对代码进行了改写,返回HttpResponseMessage, 限定返回的ContentType 为application/json, 改写后代码如下

        [HttpGet]
        [HttpQueryStringFilter("queryString")]
        public HttpResponseMessage GetWarrantySearchResult(FormDataCollection queryString)
        {
            string serialNum = queryString.HasKey("search") ? queryString.GetValue<string>("search").Trim() : string.Empty;
            var jsonError = JsonHelper.WarrantyJsonError();
            HttpResponseMessage resp = new HttpResponseMessage();
            resp.Content = new StringContent(jsonError, System.Text.Encoding.UTF8, "application/json");
            if (!string.IsNullOrEmpty(serialNum))
            {
                try
                {

                    //Send SOAP Request
                    WebRequest webRequest = WebRequest.Create("http://gglnzdom1/pec/product.nsf/getWarranty?WSDL");
                    HttpWebRequest httpRequest = (HttpWebRequest)webRequest;
                    httpRequest.Method = "POST";
                    httpRequest.ContentType = "text/xml; charset=utf-8";
                    httpRequest.ProtocolVersion = HttpVersion.Version11;
                    httpRequest.Credentials = CredentialCache.DefaultCredentials;
                    Stream requestStream = httpRequest.GetRequestStream();
                    //Create Stream and Complete Request             
                    StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.ASCII);

                    string soapRequest = "<soapenv:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:urn='urn:DefaultNamespace'><soapenv:Header/><soapenv:Body><urn:GETWARRANTYARRAY soapenv:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'><SERIAL xsi:type='xsd:string'>" + serialNum + "</SERIAL></urn:GETWARRANTYARRAY></soapenv:Body></soapenv:Envelope>";
                    streamWriter.Write(soapRequest.ToString());
                    streamWriter.Close();

                    //Get SOAP response
                    HttpWebResponse wr = (HttpWebResponse)httpRequest.GetResponse();
                   
                    StreamReader srd = new StreamReader(wr.GetResponseStream());
                    string resultXmlFromWebService = srd.ReadToEnd();

                   

                    if (resultXmlFromWebService.Contains("Serial Number not found</OILCOMPANY>"))
                    {
                        return resp;


                    }
                    else if (resultXmlFromWebService.Contains("<faultstring>"))
                    {
                        return resp;


                    }
                    else
                    {
                        var resultXml = resultXmlFromWebService.Replace(" xsi:type=\"xsd:string\"", "");

                        var warrantyInfo = resultXml.Substring(resultXml.IndexOf("<WARRANTY>") + 10, resultXml.IndexOf("</WARRANTY>") - (resultXml.IndexOf("<WARRANTY>") + 10));
                        bool hasWarranty = false;
                        DateTime warrantyDate;
                        var warrantyDateStr = "";
                        if (DateTime.TryParse(warrantyInfo, out warrantyDate))
                        {
                            hasWarranty = true;
                            
                        }
                        if (hasWarranty)
                            warrantyDateStr = UmbracoFuelHelper.FormatDateString(warrantyInfo);


                        var warrantyResult = new WarrantySearchResult()
                        {
                            SerialNumber = serialNum,
                            Company = resultXml.Substring(resultXml.IndexOf("<OILCOMPANY>") + 12, resultXml.IndexOf("</OILCOMPANY>") - (resultXml.IndexOf("<OILCOMPANY>") + 12)) + " " + resultXml.Substring(resultXml.IndexOf("<COUNTRY>") + 9, resultXml.IndexOf("</COUNTRY>") - (resultXml.IndexOf("<COUNTRY>") + 9)),
                            Site = resultXml.Substring(resultXml.IndexOf("<SITE>") + 6, resultXml.IndexOf("</SITE>") - (resultXml.IndexOf("<SITE>") + 6)),
                            Customer = resultXml.Substring(resultXml.IndexOf("<CUSTOMER>") + 10, resultXml.IndexOf("</CUSTOMER>") - (resultXml.IndexOf("<CUSTOMER>") + 10)),
                            DespatchDate = UmbracoFuelHelper.FormatDateString(resultXml.Substring(resultXml.IndexOf("<DESPATCHED>") + 12, resultXml.IndexOf("</DESPATCHED>") - (resultXml.IndexOf("<DESPATCHED>") + 12))),
                            HasWarranty = hasWarranty,
                            WarrantyDate = warrantyDateStr

                        };



                        var jsonWarranty = JsonHelper.getJsonByObject(warrantyResult);

                      
                        resp.Content = new StringContent(jsonWarranty, System.Text.Encoding.UTF8, "application/json");


                      
                        return resp;

                        //return JsonConvert.SerializeObject(jsonWarranty);

                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }
            else
            {
                return resp;
            }


        }

现在返回的就是JSON

{"company":"Aus 7-11 Mobil Australia","customer":"ECL Group Australia Pty Ltd","dispatch_date":"2015-02-12","has_warranty":false,"serial_number":"1401410","site":"2273 West Ryde","warranty_date":""}

 

posted on 2016-09-30 07:54  新西兰程序员  阅读(2936)  评论(0编辑  收藏  举报