在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") : "";
string category = queryStrings.HasKey("category") ? queryStrings.GetValue<string>("category") : "";
string docType = queryStrings.HasKey("docType") ? queryStrings.GetValue<string>("docType") : "";
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":"","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":"","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>") + , resultXml.IndexOf("</WARRANTY>") - (resultXml.IndexOf("<WARRANTY>") + ));
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>") + , resultXml.IndexOf("</OILCOMPANY>") - (resultXml.IndexOf("<OILCOMPANY>") + )) + " " + resultXml.Substring(resultXml.IndexOf("<COUNTRY>") + , resultXml.IndexOf("</COUNTRY>") - (resultXml.IndexOf("<COUNTRY>") + )),
Site = resultXml.Substring(resultXml.IndexOf("<SITE>") + , resultXml.IndexOf("</SITE>") - (resultXml.IndexOf("<SITE>") + )),
Customer = resultXml.Substring(resultXml.IndexOf("<CUSTOMER>") + , resultXml.IndexOf("</CUSTOMER>") - (resultXml.IndexOf("<CUSTOMER>") + )),
DespatchDate = UmbracoFuelHelper.FormatDateString(resultXml.Substring(resultXml.IndexOf("<DESPATCHED>") + , resultXml.IndexOf("</DESPATCHED>") - (resultXml.IndexOf("<DESPATCHED>") + ))),
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":""}

ASP.NET Web Api返回对象类型为JSON还是XML的更多相关文章

  1. ASP.NET Web API 路由对象介绍

    ASP.NET Web API 路由对象介绍 前言 在ASP.NET.ASP.NET MVC和ASP.NET Web API这些框架中都会发现有路由的身影,它们的原理都差不多,只不过在不同的环境下作了 ...

  2. ASP.NET WEB API 返回JSON 出现2个双引号问题

    前言          在使用ASP.NET WEB API时,我想在某个方法返回JSON格式的数据,于是首先想到的就是手动构建JSON字符串,如:"{\"result\" ...

  3. ASP.NET Web API 2 媒体类型格式化程序

    Ø  简介 在之前的ASP.NET Web API 2 消息处理管道文章中有提到,在 Web API 的生命周期中,还包含比较中要的一部分,就是媒体类型格式化程序,该程序主要用于处理 Web API ...

  4. ASP.NET Web API 2.1支持Binary JSON(Bson)

    ASP.NET Web API 2.1内建支持XML.Json.Bson.form-urlencoded的MiME type,今天重点介绍下Bson.BSON是由10gen开发的一个数据格式,目前主要 ...

  5. Asp.net Web API 返回Json对象的两种方式

    这两种方式都是以HttpResponseMessage的形式返回, 方式一:以字符串的形式 var content = new StringContent("{\"FileName ...

  6. asp.net web api返回图片至前端

    var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new ByteArrayContent(da ...

  7. ASP.NET Web API 2 入门(一)

    前言 HTTP 不是只是为了服务的 web 页.这也是建设公开服务和数据的 Api 的强大平台.HTTP 是简单的. 灵活的和无处不在.你能想到的几乎任何平台有 HTTP 库,因此,HTTP 服务可以 ...

  8. ASP.NET Web API WebHost宿主环境中管道、路由

    ASP.NET Web API WebHost宿主环境中管道.路由 前言 上篇中说到ASP.NET Web API框架在SelfHost环境中管道.路由的一个形态,本篇就来说明一下在WebHost环境 ...

  9. ASP.NET Web API Selfhost宿主环境中管道、路由

    ASP.NET Web API Selfhost宿主环境中管道.路由 前言 前面的几个篇幅对Web API中的路由和管道进行了简单的介绍并没有详细的去说明一些什么,然而ASP.NET Web API这 ...

随机推荐

  1. UVALive 5713 Qin Shi Huang's National Road System(次小生成树)

    题意:对于已知的网络构建道路,使城市两两之间能够互相到达.其中一条道路是可以免费修建的,问需要修建的总长度B与免费修建的道路所连接的两城市的人口之和A的比值A/B最大是多少. 因为是求A/B的最大值, ...

  2. 【Java学习笔记】数组使用

    package aaa; public class aaa { public static void main(String args[]) { int a[]={1,2,3,4}; for(int ...

  3. DrawDib函数组的使用

    Microsoft的针对与设备无关位图(DIB位图),在其WIN32 SDK的Multimedia中提供了一组绘制DIB位图的高性能函数组──DrawDib函数组.DrawDib函数组是一组不依赖于图 ...

  4. 移动开发之浅析cocos2d-x的中文支持问题

    题记:这阵子一直在学习cocos2d-x,其跨平台的特性确实让人舒爽,引擎的框架概念也很成熟,虽然相应的第三方工具略显单薄,但也无愧是一件移动开发的利器啊,有兴趣的朋友有时间就多了解吧. 使用引擎的过 ...

  5. 转载RabbitMQ入门(2)--工作队列

    工作队列 (使用Java客户端) 在这第一指南部分,我们写了通过同一命名的队列发送和接受消息.在这一部分,我们将会创建一个工作队列,在多个工作者之间使用分布式时间任务. 工作队列(亦称:任务队列)背后 ...

  6. 【转】第一次使用Android Studio时你应该知道的一切配置

    原文网址:http://www.cnblogs.com/smyhvae/p/4390905.html [声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.c ...

  7. FTP文件上传与下载

    实现FTP文件上传与下载可以通过以下两种种方式实现(不知道还有没有其他方式),分别为:1.通过JDK自带的API实现:2.通过Apache提供的API是实现. 第一种方式:使用jdk中的ftpClie ...

  8. android电池信息简介

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...

  9. android桌面小火箭升空动画

    public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceS ...

  10. 扩展Fitnesse的ScriptTable:支持if-then

    Fitnesse的ScriptTable只能顺序执行所有行,本博文介绍如何让ScriptTable支持if-then,来条件执行一行. 首先普及一下概念,什么是Fitnesse,听一听.NET版Cuc ...