I am sending xml/mathml as data in my AJAX request, and at the server side in C# I get this sort of text:
%3Cmath%3E%0A%20%20%20%20%3Cmrow%3E%0A%20%20%20%20%20%20%20%20%3Cmsub%3E%0A%20%20%20%20%20%20%20%20%20%20%20%20%3Cmi%3Ex%3C%2Fmi%3E%0A%20%20%20%20%20%20%20%20%20%20%20%20%3Cmtext%3E12%3C%2Fmtext%3E%0A%20%20%20%20%20%20%20%20%3C%2Fmsub%3E%0A%20%20%20%20%20%20%20%20
So, basically it is xml, but the xml basic characters are converted to url like characters, %20, %3E, %0A etc...
I have this POST method in my API controller:
[HttpPost]
public HttpResponseMessage PostUpload(HttpRequestMessage req)
{
string jsonContent = req.Content.ReadAsStringAsync().Result;
Utility.Utility.WriteLineToConsole("json data post: " + jsonContent);
return Request.CreateResponse(HttpStatusCode.OK, jsonContent);
}
The Utility function WriteLineToConsole() prints the jsonContent and the top text among the result.
How can i covert the string above to xml, i.e replace the url-like characters to xml characters?
Note: I am using MVC 4 / C# , jQuery AJAX, and both contentType and dataType are of type json. I want my data object to be like
data:{mathml: "<math>...</math>"}
HttpUtility.UrlDecode(thatString)
did the job
Related
I have a REST API written in C #. Method DoQuery send query to the database, and get json as response
public async Task<QueryResponseDto> DoQuery(string request)
{
return await _dbConnection.QuerySingleAsync<QueryResponseDto>("select web.json_request('" + request + "') as response;",commandTimeout:600);
}
...
[HttpPost]
[Route("DoQuery")]
public async Task<string> DoQuery([FromBody] object body)
{
var r = await _dataService.DoQuery(JsonSerializer.Serialize(body));
return r.response;
}
When I run query in database, I get correct json answer like this
[
{
"contractor":{
"ek2id":"91707d21-50f3-4aa4-8209-e80b963da99d",
"externalids":[
{
"externalsource":"SBL",
"externalid":"1-4OB8C75"
}
]
}
}
]
But when I run method DoQuery from PostMan I get escaped response like this
"[{\"contractor\":{\"ek2id\":\"91707d21-50f3-4aa4-8209-e80b963da99d\",\"externalids\":[{\"externalsource\":\"SBL\",\"externalid\":\"1-4OB8C75\"}]}}]"
How can I get normal unescaped response from REST API?
When you query the database it formats the JSON for you when it displays the output. The actual value in the database could be some UTF8, or similar encoding.
If escape is causing issue you could try storing actual UTF8 value for quotes in the string. But in both the cases you need to encode the response.
With a simple C# AWS Lambda
public string FunctionHandler(string myParam1, ILambdaContext context)
{
return myParam1;
}
How should I pass parameters to an AWS Lambda function + API Gateway, via a browser GET request?
I'd like something like this for example:
https://[API ID].execute-api.[REGION].amazonaws.com/myFunc?myParam1=myValue1
In the browser it says {"message":"Internal Server Error"}
In the logs it says Error converting the Lambda event JSON payload to a string. JSON strings must be quoted, for example "Hello World" in order to be converted to a string: The JSON value could not be converted to System.String.
Without parameters it works, for example:
public string FunctionHandler(ILambdaContext context)
{
return Utf8Json.JsonSerializer.ToJsonString(context);
}
When sending a GET request in the browser https://[API ID].execute-api.[REGION].amazonaws.com/myFunc returns successfully {"AwsRequestId":"86ca2da9-438c-4865-8a0b-29d3ced37176","FunctionName":....
Ok I found a solution, instead of using the built-in parsing of parameters, it's possible to read a full JSON of parameters by reading a stream instead:
public string FunctionHandler(Stream requestStream, ILambdaContext context) { ... }
The requestStream here will have the parameters of GET/POST inside or a larger JSON, but have to be manually parsed. Note that the parameters may be sent b64 encoded (or probably also compressed). A good way would be to find a library which does this parsing.
In my case, I also write the consumer JS code, so I can ensure the parameters will always come in the same fashion so my problem is solved but if someone has knows a good library for this, please tell.
Example of a manual POST request data extraction which also supports b64 encoding:
public class StreamBody
{
public string body;
public bool isBase64Encoded;
}
public string FunctionHandler(Stream requestStream, ILambdaContext context)
{
using var sr = new StreamReader(requestStream);
var input = sr.ReadToEnd();
var sbody = Utf8Json.JsonSerializer.Deserialize<StreamBody>(input);
var body = !sbody.isBase64Encoded ? sbody.body : Encoding.UTF8.GetString(Convert.FromBase64String(sbody.body));
I have been using some simple requests in past to send JSON and they have been working fine. I basically take simple string, convert it to UTF-8 using
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
and send this using HttpWebRequest.
Now I have received a task to send a new POST request which will have an array of Ids and be of type
{
"GroupID": "Named_ID",
"ChildIds": [
"76197272-24E4-4DD2-90B8-46FDDCC0D6CA",
"D2B3A1AC-ACF6-EA11-A815-000D3A49E4F3",
"ED53D968-00F4-EA11-A815-000D3A49E4F3"
]
}
The ChildIds are available in a List(String []) with me. I could loop through the records and create a similar long string and then convert to byteArray in UTF8 but I feel this can be done in a simpler way. Examples that I have seen on the forum of using array in JSON always appear to use JsonConvert.SerializeObject but I am not clear if I should use this and if I do then do I convert the serialised object to UTF8 like I did earlier and is it then ok to use in the HttpWebRequest.
Can someone please advice on the approach I should take.
Create a class structure to match your json,
public class Data
{
public string GroupId {get;set;}
public List<string> ChildIds {get;set;}
}
serialize the data with JsonConvert or any other.
var json = JsonConvert.SerializeObject<Data>(str) ;
Post the serialized data with httpclient assuming you have it injected in your class already.
var data = new StringContent(json, Encoding.UTF8, "application/json");
var post = await client.PostAsync(url, data);
I'm trying to return a base64 string representing a jpeg image from an API Controller and set it as the src of an <img> but all my attempts failed.
Here is the very simple HTML:
<img src="/api/TestBase64Image" alt="image test" />
And my controller:
[Route("api/[controller]")]
public class TestBase64ImageController : Controller
{
private const string _base64Image = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/7Sfg.....";
private const string _base64Image2 = "/9j/4AAQSkZJRgABAQEBLAEsAAD/7Sfg.....";
[HttpGet]
public async Task Get()
{
Response.ContentType = "image/jpeg";
//Response.ContentType = "text/plain";
//Response.ContentType = new MediaTypeHeaderValue("image/jpeg").ToString();
//Response.ContentType = new MediaTypeHeaderValue("text/plain").ToString();
//Response.Headers.Add("Content-Length", _base64Image.Length.ToString());
//HttpContext.Response.ContentLength = _base64Image.Length;
await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(_base64Image), 0, _base64Image.Length);
//await Response.Body.FlushAsync();
}
}
I've tried several things, like removing FlushAsync(), changing the way to define the ContentType, include data:image/jpeg;base64, in the string or not but nothing is working.
I've seen here and here that writing in the Response body stream is doable, so I presume I'm on the good way (I've tried to return a simple string before but not working as well).
Yes my base64 string is correct because I've also tried to include it directly into the HTML and the image shows up correctly.
I precise I don't want to use any JavaScript or Razor view to achieve that, only pure HTML and my controller.
Also please pay attention that I'm inside an API Controller. I can't do the same as we see in the Configure method in the Startup class of an empty ASP.NET Core project like:
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
Even though both Responses' types are HttpResponse, the one in my controller doesn't have any Response.WriteAsync but Response.Body.WriteAsync
Thanks for your help, it's been hours I'm searching but there is almost no resources about this yet for ASP.NET Core
You're still returning the data as base64 text, basically - you're getting the UTF-8 encoded form of it, but that's all.
If you really only have the base64 version of the image, you just need to decode that:
byte[] image = Convert.FromBase64String(_base64Image2);
await Response.Body.WriteAsync(image, 0, image.Length);
(Note that it needs to be just the base64 you convert - not the data URI.)
I am trying to get data from a URL that contains JSON values. These values are to be used in my windows 8 desktop app. The code I have tried is seen below.
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(App.DataServiceUrl + "/productcategory");
var Groups = new List<GroupList>();
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var prods = JsonConvert.DeserializeObject<dynamic>(content);
foreach (var data in prods)
{
var dataGroup = new GroupList
(
data.term_id,
data.name,
data.slug,
data.description,
data.taxonomy
);
Groups.Add(dataGroup);
}
}
The URL I am accessing is actually a page in a website where I call some fucntions to get some data in php and then use json_encode($all); to return json data. When I access the url, I can see all the JSON data.
One example of the data from URL is:
[{"term_id":"64","name":"Argentina","slug":"argentina","term_group":"0","term_taxonomy_id":"64","taxonomy":"product_cat","description":"","parent":"13","count":"20","meta_id":"154","woocommerce_term_id":"64","meta_key":"order","meta_value":"0","cat_ID":"64","category_count":"20","category_description":"","cat_name":"Argentina","category_nicename":"argentina","category_parent":"13"},...]
But the application doesn't recognize the json values when I try to access them such as term_id, name etc. (as seen in code above)
Instead when I run the application I get this error:
Unexpected character encountered while parsing value: <. Path", line 4, position 2
How do I get and use the values from the url in my C# code?
You could use the DynamicJson class to parse the JSON, as far as I know it's the best option.
Your page produces some random text in front of JSON. You can take any HTTP debugger (my favorite is Fiddler, but anything would do) to confirm. Here are first several lines of the response from http://cbbnideas.com/brydens-website/api/ - note that JSON starts at 8th line:
37
<!--All Categories (And Sub Categories)-->
6bd8
[{"term_id":"64","name":"Argentina","slug":"argentina","term_gr...