Strings Sent Through Web API's Gets Wrapped in Quotes

Strings sent through Web API's gets wrapped in quotes

After MUCH research, I finally figured this one out.

First off; I was returning the HttpResponseMessage directly; I was not intentionally deserializing it inside each hop along the API-path.

The problem, as it turns out, was actually that we were using a mix of the "native" MVC serialization methods and JSON.net's methods. Either one by itself is fine, and provides a clean passthrough of all API's. If, however, we would combine serialized data from both native methods and JSON.net-methods, the API's further down the chain would not be able to recognize the formatting and incorrectly assume that the content should be serialized again (using native methods).

So the solution was simply to remove all JSON.net-methods from the serialization process, and we ended up with the expected results.

ASP.NET Core API sending string wrapped in double quotes

As discussed in the comments you have a [Produces] attribute on the class that is forcing a JSON response. From the docs on ProducesAttribute we can see it can be applied to an action as well as the controller. So, you can override for a particular action by adding it there, in your case you need text/plain:

[Produces("text/plain")]
public async Task<IActionResult> GetSAS(string blobUri, string _method)
{
//snip
}

FromBodyAttribute with string parameter requires double quotes of JSON ASP.NET CORE 2.1

We use DefaultContractResolver class which is the part of Newtonsoft.Json.Serialization. The code will look like as below.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddJsonOptions(opt =>
{
if (opt.SerializerSettings.ContractResolver != null)
{
var resolver = opt.SerializerSettings.ContractResolver as DefaultContractResolver;
resolver.NamingStrategy = null;
}
});
}

webapi2 return simple string without quotation mark

Yes you can avoid the "

public class ValuesController : ApiController
{
public string Get()
{
return "qwerty";
}
}

now check http://localhost:3848/api/values

and response

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">qwerty</string>

The result with <string> tag but without quotes :)

EDIT

If you don't like this approach,try this.It returns just text

public HttpResponseMessage Get()
{
string result = "Your text";
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
return resp;
}

Web Api: recommended way to return json string

Create custom implementation. The framework is extensible via the IHttpActionResult.

The following creates a custom result and extension method...

public static class JsonStringResultExtension {
public static CustomJsonStringResult JsonString(this ApiController controller, string jsonContent, HttpStatusCode statusCode = HttpStatusCode.OK) {
var result = new CustomJsonStringResult(controller.Request, statusCode, jsonContent);
return result;
}

public class CustomJsonStringResult : IHttpActionResult {
private string json;
private HttpStatusCode statusCode;
private HttpRequestMessage request;

public CustomJsonStringResult(HttpRequestMessage httpRequestMessage, HttpStatusCode statusCode = HttpStatusCode.OK, string json = "") {
this.request = httpRequestMessage;
this.json = json;
this.statusCode = statusCode;
}

public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) {
return Task.FromResult(Execute());
}

private HttpResponseMessage Execute() {
var response = request.CreateResponse(statusCode);
response.Content = new StringContent(json, Encoding.UTF8, "application/json");
return response;
}
}
}

...that can then be applied to ApiController derived classes. Greatly simplifying previous calls to

return this.JsonString(jsonUtilizadores); //defaults to 200 OK

or with desired HTTP status code

return this.JsonString(jsonUtilizadores, HttpStatusCode.BadRequest);

JSON objects being returned from Express API with quotes -- why? and how to resolve?

readFile returns a string. you will need to JSON.parse(readFile) and send that.

Your route would need to be somethign like

router.get('/projects', function (req, res) {
logic.getProjects()
.then(projects => JSON.parse(projects))
.then(jsonProjects => res.json(jsonProjects))
.catch(err => console.error(err))

Pass list of strings from client to web api

GET requests do not have a BODY, you can use query string values. ?dates='{UrlEncoded date}'&dates='{UrlEncoded date}'...

public HttpResponseMessage Get([FromUri] List<string> dates) {
//..... function going here
}

On the client side you would need to construct the query string and append it to the Uri

var dates = datelist.Select(d => string.Format("dates={0}", UrlEncode(d));
var query = string.Join("&", dates);
var uri = "api/dataAccessApi?" + query;

With UrlEncode looking like this

/// <summary>Escape RFC3986 String</summary>
static string UrlEncode(string stringToEscape) {
return stringToEscape != null ? Uri.EscapeDataString(stringToEscape)
.Replace("!", "%21")
.Replace("'", "%27")
.Replace("(", "%28")
.Replace(")", "%29")
.Replace("*", "%2A") : string.Empty;
}

For Asp.Net Core consider to use [FromQuery] instead of [FromUri]

strings returned by wcf wrapped with extra quotes

I have had this problem with iPhone developers in my workplace. The workaround I used was returning a custom class object instead of String like following:

public class StringContainer
{
public String Value { get; set; }
}


Related Topics



Leave a reply



Submit