ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

WebService返回JSON格式(转载)

2022-05-05 15:00:35  阅读:258  来源: 互联网

标签:WebService JSON User output override 格式 public string Name


原文地址:https://www.cnblogs.com/liweis/p/12594202.html

WebService是基于XML格式的,返回的默认结果是XML格式,因为它比较通用,几乎任何编程语言、操作系统和应用程序都能方便的读写。

多番测试

方式一:最简单的例子:

1 2 3 4 5 6 [WebMethod(MessageName = "默认返回对象")] public User GetXmlByObject() {     User user = new User() {Id = 1, Name = "张三"};     return user; }

 返回结果:

1 2 <?xml version="1.0" encoding="UTF-8"?> <User xmlns="http://tempuri.org/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Id>1</Id><Name>张三</Name></User>

 方式二:WebService的输入或输出参数可以是对象,它会自动序列化XML格式,如果自己强加序列化一次,返回字符串,结果就是这样:

1 2 3 4 5 6 [WebMethod(MessageName = "构造XML返回")] public string GetXmlByXml() {     User user = new User() { Id = 2, Name = "张三丰" };     return SerializeToXml(user); }

返回结果:

1 2 <?xml version="1.0" encoding="UTF-8"?> <string xmlns="http://tempuri.org/"><?xml version="1.0" encoding="utf-8"?><User xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Id>2</Id><Name>张三丰</Name></User></string>

 方式三:随着JSON的流行,更多的网页、移动端都需要JSON格式。于是,就把它序列化JSON串返回(我一直都是这样操作的)

1 2 3 4 5 6 7 [WebMethod(MessageName = "构造JSON返回")] public string GetXmlByJson() {     User user = new User() { Id = 3, Name = "李四" };     //添加Newtonsoft.Json进行序列化     return JsonConvert.SerializeObject(user); }

返回结果:

1 2 <?xml version="1.0" encoding="UTF-8"?> <string xmlns="http://tempuri.org/">{"Id":3,"Name":"李四"}</string>

 方式四:如果将对象反序列化成JSON字符串,返回包含json字符串的XML格式,前端总要有一个解析过程,不是很方便!有没有返回直接是JSON格式的?有。

1 2 3 4 5 6 7 [WebMethod(MessageName = "Response.Write")] public void GetXmlByResponse() {     User user = new User() { Id = 4, Name = "李世民" };     Context.Response.Write(JsonConvert.SerializeObject(user));     Context.Response.End(); }

返回结果:

1 {"Id":4,"Name":"李世民"}

解决方案

上面最后一 种测试虽然能达到效果,但每个接口中都要这样操作,显得有点"笨",当然想要高级的自行车。

第一步,在工程中新建AsmxRequestModule.cs和CatchTextStream.cs文件,并实现它。

AsmxRequestModule代码如下:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public class AsmxRequestModule: IHttpModule {     public void Init(HttpApplication context)     {         context.BeginRequest += new EventHandler(Application_BeginRequest);     }       public void Dispose()     {     }       public void Application_BeginRequest(object sender, EventArgs e)     {         HttpApplication application = sender as HttpApplication;         string extension = Path.GetExtension(application.Request.Path);         if (application.Request.Path.IndexOf(".asmx/") > -1)         {             application.Response.Filter = new CatchTextStream(application.Response.Filter);         }     } }

CatchTextStream代码如下:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 public class CatchTextStream: Stream {     #region 数据流     /// <summary>     /// 数据流     /// </summary>     private readonly Stream output;     #endregion     #region 构造函数     public CatchTextStream(Stream s)     {         output = s;     }     #endregion     #region 重载属性及方法     public override bool CanRead => output.CanRead;       public override bool CanSeek => output.CanSeek;       public override bool CanWrite => output.CanWrite;       public override void Flush()     {         output.Flush();     }     public override long Length => output.Length;       public override long Position     {         get => output.Position;         set => output.Position = value;     }     public override int Read(byte[] buffer, int offset, int count)     {         return output.Read(buffer, offset, count);     }     public override long Seek(long offset, SeekOrigin origin)     {         return output.Seek(offset, origin);     }     public override void SetLength(long value)     {         output.SetLength(value);     }     public override void Write(byte[] buffer, int offset, int count)     {         if (HttpContext.Current != null)         {             HttpContext context = HttpContext.Current;             Encoding encoding = context.Response.ContentEncoding;             string responseInfo = encoding.GetString(buffer, offset, count);             responseInfo = responseInfo.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<string xmlns=\"http://tempuri.org/\">""");             responseInfo = responseInfo.Substring(0, responseInfo.Length - 9);             buffer = encoding.GetBytes(responseInfo);             output.Write(buffer, 0, buffer.Length);         }     }     #endregion }

第二步,修改web.config ,在配置中增加modules配置。

1 2 3 4 5 6 7 8 9 10 11 <configuration>   ……  <system.webServer>     ……     <modules>       <add name="AsmxRequestModule" type="命名空间.AsmxRequestModule"/>     </modules>     ……   </system.webServer>   …… </configuration>

 第三步,按“构造JSON对象”(第三种)的方式书写接口即可。

标签:WebService,JSON,User,output,override,格式,public,string,Name
来源: https://www.cnblogs.com/shuaimeng/p/16224771.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有