How do I get the binary data of the buffer in C#?
item = {[_buffer, JVBERi0xLjMKJeLjz9MKMiAwIG9iago8PAovQ3JlYXRpb25EYXR]}
I tried this but get an error:
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var dataStream = response.Content.ReadAsStringAsync().Result;
var parsed = JObject.Parse(dataStream);
if (dataStream == null)
return HttpNotFound();
foreach (dynamic item in parsed)
{
// If user decides to save the file, this will help...
Response.AddHeader("content-disposition", "filename=" + Path.GetFileName(fileDoc));
return File(item._buffer, "application/pdf");
}
}
Assuming your raw JSON looks something like this:
{
"_buffer": "JVBERi0xLjMKJeLjz9MKMiAwIG9iago8PAovQ3JlYXRpb25EYXRlIChEOjIwMTgwMTI2MjI0ODI1LTA1JzAwJykKL01vZERhdGUgKEQ6MjAxODAxMjYyMjQ4MjUtMDUnMDAnKQovUHJvZHVjZXIgKEJDTCBlYXN5UERGIDcuMDAgXCgwMzU1XCkpCi9DcmVhdG9yIChlYXN5UERGIFNESyA3IDcuMCkKPj4KZW5kb2JqCgo4"
}
Then the value of the "_buffer" property would appear to be Base64 encoded binary. As documented in its serialization guide Json.NET supports automatically deserializing Base64 strings to byte []. Thus you can do:
var _buffer = JsonConvert.DeserializeAnonymousType(dataStream, new { _buffer = (byte[])null })._buffer;
Then pass the returned byte array to Controller.File(Byte[], String).
By using JsonConvert.DeserializeAnonymousType() you avoid the need to load your (possibly large) response into an intermediate JToken hierarchy, and also avoid the need to create an explicit, concrete type just to deserialize a single byte [] property.
Related
I have a TextReader which reads from a JSON file, I want to convert that JSON into a XML, which I can do via following code.
public static XDocument? LoadXNode(TextReader textReader, string deserializeRootElementName)
{
var settings = new JsonSerializerSettings
{
Converters = { new XmlNodeConverter { DeserializeRootElementName = deserializeRootElementName } },
};
using var jsonReader = new JsonTextReader(textReader) { CloseInput = false };
return JsonSerializer.CreateDefault(settings).Deserialize<XDocument>(jsonReader);
}
However, I would like the method above to accept a stream writer as a parameter and write the Xml to that StreamWriter. By the way the mentioned StreamWriter is used to write to response.Body inside of a ASP .NET API. The goal of this is to load a json file and return it to the API consumer in the XML format is the most efficient way possible. That's why I want to skip the step, where I first deserialize the XML and then write it to the StreamWriter.
I have the following API code to get a single result response but i get error json.net complaining
when i remove this line var Product = prdList .FirstOrDefault(a => a.ID == productID); and return Json(prdList); it works fine but return every row in a table. how can i get a single record?
Here is the code
[HttpGet("{productID}")]
public async Task<IActionResult> Getproduct(int productID)
{
var prdList = (await rpsService.Getrps(productID)).ToList();
var Product = prdList .FirstOrDefault(a => a.ID == productID);
return Json(Product);
}
Here is the error im getting, i retrive the right information but i get error when i load the page
JsonSerializationException: Cannot deserialize the current JSON object
(e.g. {"name":"value"}) into type 'System.Collections.Generic.IList`1
Project name' because the type requires a JSON array (e.g. [1,2,3]) to
deserialize correctly. To fix this error either change the JSON to a
JSON array (e.g. [1,2,3]) or change the deserialized type so that it
is a normal .NET type (e.g. not a primitive type like integer, not a
collection type like an array or List) that can be deserialized
from a JSON object. JsonObjectAttribute can also be added to the type
to force it to deserialize from a JSON object. Path 'productID', line
1, position 13.
I tried this working fine but display all rows
[HttpGet("{productID}")]
public async Task<IActionResult> GetProduct(int productID)
{
var prdList = (await rpsService.Getrps(productID)).ToList();
return Json(prdList );
}
you can directly apply condition while fetching list as mention below.
var prdList = (await rpsService.Getrps(productID)).ToList().FirstOrDefault();
Try this
var Product = prdList.Where(a => a.ID == productID).FirstOrDefault();
or
var prdList = (await rpsService.Getrps(productID)).ToList().FirstOrDefault();
return Json(prdList);
In my Ember v2.7.0 app, I need to use backend endpoint which does not return JSON payload. But it behaves like REST endpoint, so I thought I would just use DS.RESTAdapter to fetch the data and convert the payload via DS.Serializer.
Created this little Ember-twiddle, which just tries to fetch data with non-JSON payload. And it fails. As far as I can tell, it fails in DS.RESTAdapter code, trying to extract JSON from the payload. So that my serializer does not have a chance to process the data.
This seems a bit odd, because I thought that Serializer is the layer which is responsible for munching the payload.
Is it possible to use DS.RESTAdapter for querying non-JSON endpoint?
If not, what is the easiest way to have REST-like behaviour on non-JSON endpoint?
What you'll need to do here is creating your own adapter that derives from DS.RESTRAdapter and then override its ajaxOptions-method. There you could change its dataType to text instead. I imagine that they separated this into its own method for your exact purpose since it doesn't do much else.
The Ember Guides have a page about customizing adapters that can get you started, based on the original code from the Ember repository it should probably be something like this.
import DS from 'ember-data';
import Ember from 'ember';
const {
get
} = Ember;
export default DS.RESTAdapter.extend({
ajaxOptions(url, type, options) {
var hash = options || {};
hash.url = url;
hash.type = type;
hash.dataType = 'text';
hash.context = this;
if (hash.data && type !== 'GET') {
hash.contentType = 'text/plain; charset=utf-8';
}
var headers = get(this, 'headers');
if (headers !== undefined) {
hash.beforeSend = function (xhr) {
Object.keys(headers).forEach((key) => xhr.setRequestHeader(key, headers[key]));
};
}
return hash;
}
});
I have an Action method that returns JSON, for brevity, I excluded code. :
public ActionResult SetMasterLocation(string masterValue)
{
json = new JavaScriptSerializer().Serialize(masterLocation);
return Json(json, JsonRequestBehavior.AllowGet);
}
I need to call this method and access the JSON string that gets returned:
var jVendors = SetMasterLocation(masterValue);
When I run it and inspect the output, I see the JSON string in a dynamic property called Data:
But if I try to access data like this, the app will not compile because the compiler says Cannot resolve symbol 'Data':
var jVendors = SetMasterLocation(masterValue);
var data = jVendors.Data;
How do I access the Data property at runtime?
Return JsonResult
return new JsonResult()
{
Data = someData,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
Then, you can access Data property of the result
I am using ServiceStack to create a C# client to a JSON RESTful service. I have this code that returns my DTO:
Search result = restClient.Get (search);
This works fine, but in order to effectively debug the search results coming back I need to output the text content from the underlying HTTP Response object. (I don't know all the elements in the response yet in order to add them to the DTO).
Is there any way I can get hold of the underlying HTTP response, and thus the full text content, from my result object?
Thanks in advance.
#adamfowleruk
When inheriting from ServiceStack's built-in Service you can access the underlying Request and Response directly from the Response class with:
public class MyService : Service
{
public object Get(Request request)
{
base.Request ...
base.Response ...
}
}
You won't see the response output in your service or filters since it writes directly to the response stream and is the last thing that ServiceStack does after executing your service and all response filters.
For diagnosing HTTP I recommend using Fiddler or WebInspector also ServiceStack's built-in Request Logger might help as well.
Consuming a ServiceStack service
If you're using the C# Service Clients you can simply ask for what you want, e.g. you can access the returned response as a raw string:
string responseJson = client.Get<string>("/poco/World");
Or as raw bytes:
byte[] responseBytes = client.Get<byte[]>("/poco/World");
Or as a Stream:
using (Stream responseStream = client.Get<Stream>("/poco/World")) {
var dto = responseStream.ReadFully().FromUtf8Bytes().FromJson<PocoResponse>();
}
Or even access the populated HttpWebResponse object:
HttpWebResponse webResponse = client.Get<HttpWebResponse>("/poco/World");
webResponse.Headers["X-Response"] //World
using (webResponse)
using (var stream = webResponse.GetResponseStream())
using (var sr = new StreamReader(stream)) {
string response = sr.ReadToEnd();
}
You can also introspect the HttpWebResponse by using Global and Local Response filters, e.g:
JsonServiceClient.HttpWebResponseFilter = httpRes => { .. };
Or using a Local filter:
var client = new JsonServiceClient(baseUrl) {
ResponseFilter = httpRes => { .. }
};
Consuming a 3rd Party Service
If you're consuming a 3rd Party REST/HTTP API you can use a responseFilter: in ServiceStack's HTTP Util extensions:
List<GithubRepo> repos = "https://api.github.com/users/{0}/repos".Fmt(user)
.GetJsonFromUrl(responseFilter: httpRes => {
var remaining = httpRes.Headers["X-Api-Remaining"];
})
.FromJson<List<GithubRepo>>();
I use Fiddler to debug my services. It gives you all sorts of cool HTTP debugging facilities.
http://www.fiddler2.com/fiddler2/
I like to use RestConsole. It is a Chrome Extension and you can easily submit POST requests and see the response. It is also handy to create sample data and then step into the ServiceStack code and see what's happening. The ServiceStack PluralSight course has a nice demo of how to use them together.
Thanks to the above help I found the right answer. Documenting here for others:-
SearchResponse result = null; // my ServiceStack DTO
HttpWebResponse webResponse = restClient.Get<HttpWebResponse>(
completePath("/v1/search",qp)); // builds the URL with parameters
using (var stream = webResponse.GetResponseStream())
using (var sr = new StreamReader(stream)) {
var text = sr.ReadToEnd();
log.log ("response text: " + text); // *** PRINTING STRING VALUE HERE FOR DEBUG
result = text.FromJson<SearchResponse>();
}
// Now do something useful with the result DTO object
log.log ("RESULT: " + result.ToString ());
for (int i = 0; i < result.Results.Length; i++) {
log.log ("Result " + i + ": " + result.Results[i].ToString());
}