应该是:

{"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. Docker常用操作命令

    docker 常用管理命令 修改镜像地址 sudo tee /etc/docker/daemon.json <<-'EOF' { "registry-mirrors": ...

  2. MySQL Root密码丢失解决方法总结

    1. 检查my.cnf,看看有没有密码......靠这也算一条啊 2. 如果能够重启,首先使用–skip-grant-tables参数重启,然后改密码,再去掉–skip-grant-tables参数重 ...

  3. 解决linux下root运行Elasticsearch异常

    如果以root身份运行将会出现以下问题 root@yxjay:/opt/elasticsearch-2.3.5/bin# ./elasticsearchException in thread &quo ...

  4. Echarts在java中使用

    index.jsp <%@ page language="java" import="java.util.*" pageEncoding="UT ...

  5. MonoDevelop Assembly Browser

    [MonoDevelop Assembly Browser] View -> Assembly Browser,通过此窗口可以查看Dll的反编译后的代码. 还有几款免费的替代产品可以使用, 虽然 ...

  6. Kafka核心概念(转)

    转自:https://blog.csdn.net/liyiming2017/article/details/82805479 1.Kafka集群结构 实际上kafka的结构图是有些区别的,现在我们看下 ...

  7. 113. Path Sum II (Tree; DFS)

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...

  8. QScopedPointer

    QScopedpointer detailed description the QScopedpointer class stores a pointer to a dynamically alloc ...

  9. ReactNative常用第三方控件

    Flex可视化在线工具 http://the-echoplex.net/flexyboxes/?fixed-height=on&legacy=on&display=flex&f ...

  10. 转载 MYSQL性能优化的最佳20+条经验

    转自:https://coolshell.cn/articles/1846.html 今天,数据库的操作越来越成为整个应用的性能瓶颈了,这点对于Web应用尤其明显.关于数据库的性能,这并不只是DBA才 ...