How to force web service methods to return a string value in string format?

How to force web service methods to return a string value in string format?

My web service method is as follows

[WebMethod] public string GetSomeLines() { System.Text.StringBuilder builder = new StringBuilder(); builder.AppendLine("Line1."); builder.AppendLine("Line2."); builder.AppendLine("Line3."); return builder.ToString(); } 

But when I get the result from a web browser or from a delphi / C # user, it will look like this:

 Line1. Line2. Line3. 

While I expect to see:

 Line1. Line2. Line3. 

I know it can return a StringBuilder or String Array here, but I want to know if there is a way to do this with the result of the string.

Thanks for your help.

+4
source share
3 answers

The AppendLine method for StringBuilder adds a default line terminator to the end of the added string. The default line terminator is the current value of the Environment.NewLine property, which is "\ r \ n" for non-Unix platforms, or "\ n" for Unix platforms. So what your WebMethod is trying to return looks like this:

"String 1.. \ R \ nLine2. \ R \ nLine3. \ R \ n".

However, the return value is serialized according to the SOAP specifications by truncating "\ r", and the result looks slightly different:

"Line1. \ NLine2. \ NLine3. \ N".

If the service consumer is running on a Windows platform, it probably ignores the single "\ n" character as garbage. Possible solutions:

  • Encode the return value in a different format, for example. into an array of bytes, therefore: return builder.ToString().ToCharArray();

  • Replace NewLine with another line that can be provided by the caller, for example. to the BR tag: return builder.Replace(Environment.NewLine, "<br/>").ToString();

  • Returns an array of strings or any other container with all lines selected.

+4
source

you can add the character '\ r \ n' at the end of each addition:

builder.Append ("String1 \ r \ n");

or as you said: appendLine

builder.AppendLine ("String 1.");

and after that, depending on your consumer, you can replace '\ r \ n' with a new line in the line. For browser

<br/> .

+1
source

use environement.newline when adding.

0
source

Source: https://habr.com/ru/post/1310363/


All Articles