应该是:

{"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. 获取lable选中时触发事件

    通常做网页时不会用radio和checkbox的原有样式, 会进行样式美化. 如何在点击checkbox时触发一个事件呢? <div class="main-checkbox" ...

  2. C++STL:流迭代器

    流迭代器是一种迭代器适配器.istream_iterator用于读取输入流,ostream_iterator用于写输出流.这些迭代器将它们所对应的流视为特定类型的元素序列.使用流迭代器时,可以用泛型算 ...

  3. jbpm角色审批

    可分配是一个部门或角色组,也可以选择一个表达式操作,提交任务时可以根据权限过滤这个部门或组的用户中选择一个可操作用户 <task name="审核">          ...

  4. js里面的三种注释方法

    javascript(js)语言里面的注释方法有三种. 第一种是多行注释"/**/",一般js文件开头,介绍作者,函数等信息. /* *author:xxx *day:2008-0 ...

  5. 【冷门】 C# 小技巧之获取变量名称

    今天在自我规范程序设计的时候,变量名匹配字符串来自配置文件,网上找了一会儿发现也有朋友在找寻这种方式,很不容易找到一个解决方案来自http://www.th7.cn/Program/net/20140 ...

  6. 封装baseControl

    package com.huawei.base; import java.io.IOException;import java.io.OutputStream;import java.io.Print ...

  7. Application.LoadLevel & Object.DontDestroyOnLoad

    [Application.LoadLevel] 只有在File->Build Setting中设置了的按钮才能被加载. 当level加载完成后,MonoBehaviour.OnLevelWasL ...

  8. mysql默认字符编码设置教程:my.ini设置字符编码

    在mysql的安装目录下找到my.ini,如果没有就把my-medium.ini复制为一个my.ini即可. 打开my.ini以后, [client] default-character-set=ut ...

  9. 【HDU5361】In Touch

    题意有n个人住在一条直线上,从左到右编号为1,2,3....n                                                                     ...

  10. Xen的源码安装及dom0,domU的设置

    Xen作为一种应用广泛的虚拟机方案,无论是在工业还是教育领域都发挥着巨大的作用.Xen不仅有其引以为豪的Paravirtualization实现,还有基于硬件支持的HVM实现.对于Xen,Ubuntu ...