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") : "";
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的更多相关文章
- ASP.NET Web API 路由对象介绍
ASP.NET Web API 路由对象介绍 前言 在ASP.NET.ASP.NET MVC和ASP.NET Web API这些框架中都会发现有路由的身影,它们的原理都差不多,只不过在不同的环境下作了 ...
- ASP.NET WEB API 返回JSON 出现2个双引号问题
前言 在使用ASP.NET WEB API时,我想在某个方法返回JSON格式的数据,于是首先想到的就是手动构建JSON字符串,如:"{\"result\" ...
- ASP.NET Web API 2 媒体类型格式化程序
Ø 简介 在之前的ASP.NET Web API 2 消息处理管道文章中有提到,在 Web API 的生命周期中,还包含比较中要的一部分,就是媒体类型格式化程序,该程序主要用于处理 Web API ...
- 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开发的一个数据格式,目前主要 ...
- Asp.net Web API 返回Json对象的两种方式
这两种方式都是以HttpResponseMessage的形式返回, 方式一:以字符串的形式 var content = new StringContent("{\"FileName ...
- asp.net web api返回图片至前端
var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new ByteArrayContent(da ...
- ASP.NET Web API 2 入门(一)
前言 HTTP 不是只是为了服务的 web 页.这也是建设公开服务和数据的 Api 的强大平台.HTTP 是简单的. 灵活的和无处不在.你能想到的几乎任何平台有 HTTP 库,因此,HTTP 服务可以 ...
- ASP.NET Web API WebHost宿主环境中管道、路由
ASP.NET Web API WebHost宿主环境中管道.路由 前言 上篇中说到ASP.NET Web API框架在SelfHost环境中管道.路由的一个形态,本篇就来说明一下在WebHost环境 ...
- ASP.NET Web API Selfhost宿主环境中管道、路由
ASP.NET Web API Selfhost宿主环境中管道.路由 前言 前面的几个篇幅对Web API中的路由和管道进行了简单的介绍并没有详细的去说明一些什么,然而ASP.NET Web API这 ...
随机推荐
- 学习Hadoop的资料
1)Cygwin相关资料 (1)Cygwin上安装.启动ssh服务失败.ssh localhost失败的解决方案 地址:http://blog.163.com/pwcrab/blog/static/1 ...
- C结构体之位域(位段)
C结构体之位域(位段) 有些信息在存储时,并不需要占用一个完整的字节, 而只需占几个或一个二进制位.例如在存放一个开关量时,只有0和1 两种状态, 用一位二进位即可.为了节省存储空间,并使处理简便,C ...
- error LNK2005 new,delete 等已经在LIBCMT.lib(delete.obj) 中定义 错误修正
http://blog.csdn.net/funnyskyf/article/details/5938597 1>uafxcw.lib(afxmem.obj) : error LNK2005: ...
- poj 1177 Picture (线段树 扫描线 离散化 矩形周长并)
题目链接 题意:给出n个矩形,每个矩形给左下 和 右上的坐标,求围成的周长的长度. 分析: 首先感谢大神的博客,最近做题经常看大神的博客:http://www.cnblogs.com/kuangbin ...
- btr_cur_t;
/** B-tree cursor */ typedef struct btr_cur_struct btr_cur_t; /** The tree cursor: the definition ap ...
- Codeforces Round #272 (Div. 2)
A. Dreamoon and Stairs 题意:给出n层楼梯,m,一次能够上1层或者2层楼梯,问在所有的上楼需要的步数中是否存在m的倍数 找出范围,即为最大步数为n(一次上一级),最小步数为n/2 ...
- IONIC beta.14 版本变更一览
由网友(58758323)提供 重构 视图缓存 之前用户一旦在应用程序中执行导航动作,每个退出的视图元素和scope都会被销毁.如果相同的视图再次被访问,应用程序会重新生成元素.现在,视图可以被缓存以 ...
- Java [Leetcode 160]Intersection of Two Linked Lists
题目描述: Write a program to find the node at which the intersection of two singly linked lists begins. ...
- Oracle日常维护脚本
1.正常停库流程 ps -ef|grep LOCAL=NO|cut -c 9-15|xargs kill -9 shutdown immediate; 2.备份数据库 bac ...
- mysql优化小技巧
对mysql优化时一个综合性的技术,主要包括 a: 表的设计合理化(符合3NF) b: 添加适当索引(index) [四种: 普通索引.主键索引.唯一索引unique.全文索引] c: 分表技术(水平 ...