.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 ...
随机推荐
- Android 4 学习(19):Services
参考<Professional Android 4 Development> Services Service是invisible的,因此其优先级不高于visible的Activity,之 ...
- 读《分布式一致性原理》JAVA客户端API操作3
更新数据 客户端可以通过zookeeper的API来更新一个节点的数据内容,有如下两个接口: public Stat setData(final String path, byte data[], i ...
- C# 在根据窗体中的表格数据生成word文档时出错
出错内容为:
- 10.Redis 性能测试
转自:http://www.runoob.com/redis/redis-tutorial.html Redis 性能测试是通过同时执行多个命令实现的. 语法 redis 性能测试的基本命令如下: r ...
- 页面生成柱状图 --- D3.js
转载自:https://www.cnblogs.com/fastmover/p/7779660.html D3.js从入门到"放弃"指南 前言 近期略有点诸事不顺,趁略有闲余之时, ...
- LNK2026: 模块对于 SAFESEH 映像是不安全的<转>
转自VC错误:http://www.vcerror.com/?p=162 错误描述: 在使用VS2012编译工程时,提示错误:" error LNK2026: 模块对于 SAFESEH 映像 ...
- nginx基本配置与参数说明-【转】
#运行用户 user nobody; #启动进程,通常设置成和cpu的数量相等 worker_processes 1; #全局错误日志及PID文件 #error_log logs/error.log; ...
- Javascript 键盘事件
window.document.onkeydown = function (e) { var evt = window.event || e;//兼容性处理 var keycode = evt.key ...
- select sum也会返回null值
SELECT SUM(detail.VAL) FROM AI_SDP_ORDER_MONTH_DETAIL_201706 detail 如果所有的VAL都是null的话,或者根本就不存在 ...
- centos6 安装 docker
一.升级内核(带aufs模块) 1.yum安装带aufs模块的3.10内核(或到这里下载kernel手动安装:http://down.51cto.com/data/1903250) cd /etc/y ...