.NET WCF Return String 字符串有反斜杠的处理
应该是:
{"Message":"Hello World"}
结果是:"
{\"Message\":\"Hello World\"}"
正确的写法是:
[WebGet(UriTemplate = "hello")]
public void SayHello()
{
SimpleMessage message = new SimpleMessage() {Message = "Hello World"};
string json = JsonConvert.Serialize(message);
HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
HttpContext.Current.Response.Write(json);
}
主要提示内容是:
I finally figured out a solution to this. It's not what I would have preferred (which would be to return the specific object type, and somehow instruct WCF to use a Json.Net serializer, instead of the DataContractJsonSerializer), but it is working great, and it's simple and clear.
Extending my contrived example using this new solution:
[WebGet(UriTemplate = "hello")]
public void SayHello()
{
SimpleMessage message = new SimpleMessage() {Message = "Hello World"};
string json = JsonConvert.Serialize(message);
HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
HttpContext.Current.Response.Write(json);
}
Note the return type of void. We do not return anything, since it would be serialized with DataContractJsonSerializer. Instead, I write directly to the response output stream. Since the return type is void, the processing pipeline doesn't set the content-type to the default type of "application/json", so I set it explicitly.
Because this uses HttpContext, I'm guessing it will only work if you have [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] on your service class, since that will force requests to the service to go through the ASP.NET pipeline. Without the asp.net compatibility, the HttpContext will not be available, since wcf hosting is supposed to be host agnostic.
Using this method, the results look perfect in firebug for GET requests. Correct content-type, correct content length, and raw json, not wrapped in quotes. And, I'm getting the serialization I want using Json.Net. Best of both worlds.
I'm not 100% positive of what obstacles I might run into regarding *de*serialization, when my service methods have [DataContract] object types as input parameters. I'm assuming the DataContractJsonSerializer will be used for that too. Will cross that bridge when I come to it...if it creates a problem. It hasn't so far, with my simple DTOs.
UPDATE See Oleg's answer (the UPDATE2 part). He changes the return type of the service method from void to System.ServiceModel.Channels.Message, and rather than using HttpContext.Current.Response.Write(), he uses:
return WebOperationContext.Current.CreateTextResponse (json,
"application/json; charset=utf-8", Encoding.UTF8);
Which is indeed a better solution. Thank you Oleg.
UPDATE 2 There is yet another way of accomplishing this. Change your service's return type from Message to Stream, and return this:
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
return new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));
I haven't done any specific tests, but it's possible that this would be a better choice for methods that could potentially return large amounts of data. I don't know if that matters for non-binary data though. Anyway, a thought.
原文链接是:
http://stackoverflow.com/questions/3026934/how-can-i-return-json-from-my-wcf-rest-service-net-4-using-json-net-without
.NET WCF Return String 字符串有反斜杠的处理的更多相关文章
- 如何去掉Json字符串中反斜杠
做项目的时候,遇到了这样的问题,前台传来的Json字符串在实体类中不对应(无法转换为实体类),而且传来的数据项是跟着数据库中的表的变动而变动的(不能重写实体类). 前台Json字符串为: string ...
- [转载]Python正则表达式匹配反斜杠'\'问题
转载自csdnblog:Python正则表达式匹配反斜杠'\'问题 在学习Python正则式的过程中,有一个问题一直困扰我,如何去匹配一个反斜杠(即“\”)? 一.引入 在学习了Python特殊字符和 ...
- 【python之路38】Python正则表达式匹配反斜杠“\”
一.引入 在学习了Python特殊字符和原始字符串之后,我觉得答案应该是这样的: 1)普通字符串:'\\'2)原始字符串:r'\'但事实上在提取诸如“3\8”反斜杠之前的数字时,我屡次碰壁,始终得不到 ...
- python raw String 获取字符串变量中的反斜杠
常用的获取raw string的方式为: >>>r'\n' \n 不能用在字符串变量中,获取字符串变量中的反斜杠如下: tab = '\n' >>>tab.enco ...
- String.replaceAll()方法替换字符串中的反斜杠(\)
replaceAll()方法实际是采用正则表达式的规则去匹配的. 在regex中"\\"表示一个"\",在java中一个"\"也要用&quo ...
- python 3.3.3 字面量,正则,反斜杠和原始字符串
两个不起眼但是比较重要的设定 Python str类型的字面量解释器 当反斜杠及其紧接字符无法构成一个具有特殊含义的序列('recognized escape sequences')时,Python选 ...
- addslashes() 函数返回在预定义字符之前添加反斜杠的字符串
. 预定义字符是: 单引号(') 双引号(") 反斜杠(\) NULL 提示:该函数可用于为存储在数据库中的字符串以及数据库查询语句准备字符串. 注释:默认地,PHP 对所有的 GET.PO ...
- 黄聪:PHP去掉转义后字符串中的反斜杠\函数stripslashes
addslashes函数主要是在字符串中添加反斜杠对特殊字符进行转义,stripslashes则是去掉转义后字符串中的反斜杠\,比如当你提交一段json数据到PHP端的时候可能会遇到json字符串中有 ...
- 使用java中replaceAll方法替换字符串中的反斜杠
今天在项目中使用java中replaceAll方法将字符串中的反斜杠("\")替换成空字符串(""),结果出现如下的异常: java.util.regex.Pa ...
随机推荐
- vue 时间选择器组件
vue 时间选择器组件 组件效果: 单文件组件: <template> <div class="date-pickers"> <!--date为com ...
- Redis实战——phpredis扩展安装
准备安装软件(download) 1> [redis] http://redis.googlecode.com/files/redis-2.4.3.tar.gz 2> [php ...
- dart 公共变量
dart中可以直接在一个文件里声明一个变量,这在其他语言中并不常见,比如c#语言只有类型才可以在命名空间下定义,变量必须放在类里声明 所以dart这点特性类似于js 今天就来讨论这个公共变量的作用范围 ...
- Qt(自适应窗口)
关于窗口布局: 默认控件的大小为最小尺寸: 如果此时右键设置布局时,窗口大小会自动缩放对应大小,不利于调整. 建议窗口控件设置好最小尺寸,便于窗口布局时,控件不会变形,例如: 改变minimumsiz ...
- VRRP概述
随着Internet的发展,人们对网络的可靠性的要求越来越高.对于局域网用户来说,能够时刻与外部网络保持联系是非常重要的. 通常情况下,内部网络中的所有主机都设置一条相同的缺省路由,指向出口网关(即图 ...
- MySQL数据库篇之完整性约束和表关系
主要内容: 一.完整性约束 二.表关系 1️⃣ 完整性约束 (1)何为完整性约束? 约束条件与数据类型的宽度一样,都是可选参数. 作用:用于保证数据的完整性和一致性 (2)分类主要有以下五类: 1.n ...
- mysql主从错误180301
Fatal error: The slave I/O thread stops because master and slave have equal MySQL server ids; these ...
- Think In Java 读后感
近期拜读了Think in Java 一书,这里是一些读后感. 此书不仅仅是市面上那种教会你怎么用系统API来编程的书,那种书太多. 此书不仅仅从头开始讲述了如何 ...
- go_内建变量类型
bool, string (u)int, (u)int8, (u)int16, (u)int32, (u)int64, uintptr (uintptr 是指针) byte, rune(表示字符cha ...
- Nginx源码完全注释(8)ngx_errno.c
errno.h中的strerror(int errno)可以确定指定的errno的错误的提示信息.在 Nginx 中,将所有错误提示信息预先存储在一个数组里,而预先确定这个数组的大小,是在自动化脚本中 ...