.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

时间: 2024-10-31 22:50:15

.NET WCF Return String 字符串有反斜杠的处理的相关文章

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

在做项目中,前台传来的数据为Json字符串,因为没有合适的实体来这些字段,所有就用了最简单的方式:截取字符串. 前台Json字符串为: <span style="font-size:18px;">string s1 ="[{\"ID\":\"99d2a341-ea2e-4f04-b4f4-623153d64336\",\"Name\":\"王五\",\"TotalScores

AS3中正则表达式对反斜杠的替换

一个有趣的小问题,下面的正则表达式能替换成功么? var __str:String = \'12346789\'; trace(__str.replace(/\\/g, \'5\')); 答案是:不能.trace出来的结果为: [trace] 12346789 其实正则本身并没有写错,错在被替换的字符串.反斜杠“”在AS3中是转义符,会将其后的任何值转换为本身,因此看到的字符串其实本身就是12346789,也就是没有反斜杠,当然无法搜索到. 直接trace(__str),结果和上面的trace相

php添加和删除反斜杠

1. 添加反斜杠 addslashes(string) 2. 删除反斜杠 stripslashes(string) 原文地址:https://www.cnblogs.com/jues/p/9506889.html

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

replaceAll()方法实际是采用正则表达式的规则去匹配的. 在regex中"\\"表示一个"\",在java中一个"\"也要用"\\"表示.这样,前一个"\\"代表regex中的"\",后一个"\\"代表java中的"\",所以字符串转义一次,正则转义一次,那么一个斜扛要写4个; 要想使用replaceAll()方法将字符串中的反斜杠(\)替

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

今天在项目中使用java中replaceAll方法将字符串中的反斜杠("\")替换成空字符串(""),结果出现如下的异常: 1 java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \^ 上网找了一下错误的原因:在regex中"\\"表示一个"\",在java中一个"\"也要用"\\"

正则表达式,字符串中需要两个反斜杠“\\d”

这个正则表达式为什么会有两个反斜杠? "^.*?\\.(jpg|png|bmp|gif)$"上面这个正则表达式为什么有两个反斜杠呢?反斜杠点\.就能表示点.了,为什么还要在\.前面多加一个\? ----------------- 这要分两步看首先字符串中的\\被编译器解释为\         ------->  第一步,编译器将字符串转变为"正则表达式"然后作为正则表达式,\.又被正则表达式引擎解释为.   ----------------> 第二步,才

qa:c#文本字符串插入双引号:@用法和反斜杠用法

Excel中添加超链接,可以用hyperlink公式,即=hyperlink(src,display); 在stackoverflow中的示例中:http://stackoverflow.com/questions/2905633/add-hyperlink-to-cell-in-excel-2007-using-open-xml-sdk-2-0 CellFormula cellFormula1 = new CellFormula() { Space = SpaceProcessingModeV

Python字符串和正则表达式中的反斜杠(&#39;\&#39;)问题

在Python普通字符串中 在Python中,我们用'\'来转义某些普通字符,使其成为特殊字符,比如 In [1]: print('abc\ndef') # '\n'具有换行的作用 abc defg In [2]: print('abc\tdef') # '\t'具有制位符的作用 abc defg 我们还可以用'\'来转义特殊字符,使其成为普通字符,比如 In [3]: print('abc\\tdef') # 使'\'成为一个普通的字符,没有转义作用 abc\tdef In [4]: prin

Python基础要点:字符串和正则表达式中的反斜杠(‘\‘)问题详解

给大家整理的是关于Python字符串和正则表达式中的反斜杠('\')问题以及相关知识点,有需要的朋友们可以学习下. 在Python普通字符串中 在Python中,我们用'\'来转义某些普通字符,使其成为特殊字符,比如 1 In [1]: print('abc\ndef') # '\n'具有换行的作用 2 abc 3 defg 4 5 In [2]: print('abc\tdef') # '\t'具有制位符的作用 6 abc defg 我们还可以用'\'来转义特殊字符,使其成为普通字符,比如 1