应该是:

{"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 字符串有反斜杠的处理的更多相关文章

  1. 如何去掉Json字符串中反斜杠

    做项目的时候,遇到了这样的问题,前台传来的Json字符串在实体类中不对应(无法转换为实体类),而且传来的数据项是跟着数据库中的表的变动而变动的(不能重写实体类). 前台Json字符串为: string ...

  2. [转载]Python正则表达式匹配反斜杠'\'问题

    转载自csdnblog:Python正则表达式匹配反斜杠'\'问题 在学习Python正则式的过程中,有一个问题一直困扰我,如何去匹配一个反斜杠(即“\”)? 一.引入 在学习了Python特殊字符和 ...

  3. 【python之路38】Python正则表达式匹配反斜杠“\”

    一.引入 在学习了Python特殊字符和原始字符串之后,我觉得答案应该是这样的: 1)普通字符串:'\\'2)原始字符串:r'\'但事实上在提取诸如“3\8”反斜杠之前的数字时,我屡次碰壁,始终得不到 ...

  4. python raw String 获取字符串变量中的反斜杠

    常用的获取raw string的方式为: >>>r'\n' \n 不能用在字符串变量中,获取字符串变量中的反斜杠如下: tab = '\n' >>>tab.enco ...

  5. String.replaceAll()方法替换字符串中的反斜杠(\)

    replaceAll()方法实际是采用正则表达式的规则去匹配的. 在regex中"\\"表示一个"\",在java中一个"\"也要用&quo ...

  6. python 3.3.3 字面量,正则,反斜杠和原始字符串

    两个不起眼但是比较重要的设定 Python str类型的字面量解释器 当反斜杠及其紧接字符无法构成一个具有特殊含义的序列('recognized escape sequences')时,Python选 ...

  7. addslashes() 函数返回在预定义字符之前添加反斜杠的字符串

    . 预定义字符是: 单引号(') 双引号(") 反斜杠(\) NULL 提示:该函数可用于为存储在数据库中的字符串以及数据库查询语句准备字符串. 注释:默认地,PHP 对所有的 GET.PO ...

  8. 黄聪:PHP去掉转义后字符串中的反斜杠\函数stripslashes

    addslashes函数主要是在字符串中添加反斜杠对特殊字符进行转义,stripslashes则是去掉转义后字符串中的反斜杠\,比如当你提交一段json数据到PHP端的时候可能会遇到json字符串中有 ...

  9. 使用java中replaceAll方法替换字符串中的反斜杠

    今天在项目中使用java中replaceAll方法将字符串中的反斜杠("\")替换成空字符串(""),结果出现如下的异常: java.util.regex.Pa ...

随机推荐

  1. CentOS7修改ssh端口

    http://www.cnblogs.com/rwxwsblog/p/5756894.html 修改/etc/ssh/sshd_config vi /etc/ssh/sshd_config #Port ...

  2. 基于AT UI实现表格的增删改查遇到的坑

    基于AT UI实现表格的增删改查遇到的坑 坑一.表格数据加载的渲染报错 报错:Error in render: "TypeError: Cannot read property 'isChe ...

  3. DataGrid 扩展

    //扩展表格,支持上传附件 function extendDataGrid(){ //扩展表格方法,合并单元格 ,参数为数组 $.extend($.fn.datagrid.methods, { aut ...

  4. Redis实战——简单介绍

    出自:https://www.cnblogs.com/moonlightL/p/7364107.html Redis简单介绍 Redis是一个开源,高级的键值存储和一个适用的解决方案,用于构建高性能, ...

  5. kmp(详解)

    大佬博客:https://blog.csdn.net/lee18254290736/article/details/77278769 对于正常的字符串模式匹配,主串长度为m,子串为n,时间复杂度会到达 ...

  6. MySQL中函数CONCAT及GROUP_CONCAT函数的使用

    一.CONCAT()函数 CONCAT()函数用于将多个字符串连接成一个字符串. 以数据表[user]作为实例: SELECT USER_NAME, SEX FROM USER WHERE USER ...

  7. Javascript 键盘事件

    window.document.onkeydown = function (e) { var evt = window.event || e;//兼容性处理 var keycode = evt.key ...

  8. IOS 键盘的显示与关闭

    在每一个IOS应用中,几乎不可避免的要进行文本输入操作,例如要求用户填写登陆注册信息,进行话题的评论回复,等等.用到的文本输入组件有UITextField,UITextView,对于这两个组件的相关属 ...

  9. python 中的type

    1. type(object) -> the object's type 返回的是object的类型,即对象的类定义 例如:用元类动态生成子类metaclass = type(father)   ...

  10. apt 查询软件

    apt-cache search percona-server apt list percona-server-server-5.6