I am trying to insert data into the MongoDb collection using postman. How would I approach this; hardcoding the data in JSON format works, but I want to be able to insert using postman in JSON format.
This is the code that allowed me to enter directly, using the post function in postman, with no input:
public async void Insert([FromBody]string value)
{
var client = new MongoClient();
var dbs = client.GetDatabase("test");
var collection = dbs.GetCollection<BsonDocument> ("restaurants");
BsonArray dataFields = new BsonArray { new BsonDocument {
{ "ID" , ObjectId.GenerateNewId()}, { "_id", ""}, } };
var document = new BsonDocument
{
{"borough",value },
{"cuisine","Korean"},
{"name","Bellaa"},
{"restaurant_id","143155"}
};
await collection.InsertOneAsync(document);
}
You can send it as raw data. You will set the post type to application/json.
This comes From the docs.
Related
I am returning the object directly in the GET request as following.
Ok(object);
and the response json is given as,
json data-->
{
"id":"1",
"name":"testname"
}
I want to add some more details to this json
-->
{
success:"true",
messageDetails:"The response is returned by the service",
data:{}
}
how to accomplish this?
can i club all the things in Ok(object) ??
You can make use of an anonymous type, for example:
object data = new { id = 1, name = "testname" };
return Ok(new
{
success = "true",
messageDetails = "The response is returned by the service",
data
});
I want to send file and json data from HttpClient to web api server.
I cant seem to access the json in the server via the payload, only as a json var.
public class RegulationFilesController : BaseApiController
{
public void PostFile(RegulationFileDto dto)
{
//the dto is null here
}
}
here is the client:
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["ApiHost"]);
content.Add(new StreamContent(File.OpenRead(#"C:\\Chair.png")), "Chair", "Chair.png");
var parameters = new RegulationFileDto
{
ExternalAccountId = "1234",
};
JavaScriptSerializer serializer = new JavaScriptSerializer();
content.Add(new StringContent(serializer.Serialize(parameters), Encoding.UTF8, "application/json"));
var resTask = client.PostAsync("api/RegulationFiles", content); //?ApiKey=24Option_key
resTask.Wait();
resTask.ContinueWith(async responseTask =>
{
var res = await responseTask.Result.Content.ReadAsStringAsync();
}
);
}
}
this example will work:HttpClient Multipart Form Post in C#
but only via the form-data and not payload.
Can you please suggest how to access the file and the submitted json And the file at the same request?
Thanks
I have tried many different ways to submit both file data and metadata and this is the best approach I have found:
Don't use MultipartFormDataContent, use only StreamContent for the file data. This way you can stream the file upload so you don't take up too much RAM on the server. MultipartFormDataContent requires you to load the entire request into memory and then save the files to a local storage somewhere. By streaming, you also have the benefit of copying the stream into other locations such as an Azure storage container.
This solves the issue of the binary data, and now for the metadata. For this, use a custom header and serialize your JSON into that. Your controller can read the custom header and deserialize it as your metadata dto. There is a size limit to headers, see here (8-16KB), which is a large amount of data. If you need more space, you could do two separate requests, one to POST the minimum need, and then a PATCH to update any properties that needed more than a header could fit.
Sample code:
public class RegulationFilesController : BaseApiController
{
public async Task<IHttpActionResult> Post()
{
var isMultipart = this.Request.Content.IsMimeMultipartContent();
if (isMultipart)
{
return this.BadRequest("Only binary uploads are accepted.");
}
var headerDto = this.GetJsonDataHeader<RegulationFileDto>();
if(headerDto == null)
{
return this.BadRequest("Missing X-JsonData header.");
}
using (var stream = await this.Request.Content.ReadAsStreamAsync())
{
if (stream == null || stream.Length == 0)
{
return this.BadRequest("Invalid binary data.");
}
//save stream to disk or copy to another stream
var model = new RegulationFile(headerDto);
//save your model to the database
var dto = new RegulationFileDto(model);
var uri = new Uri("NEW URI HERE");
return this.Created(uri, dto);
}
}
private T GetJsonDataHeader<T>()
{
IEnumerable<string> headerCollection;
if (!this.Request.Headers.TryGetValues("X-JsonData", out headerCollection))
{
return default(T);
}
var headerItems = headerCollection.ToList();
if (headerItems.Count() != 1)
{
return default(T);
}
var meta = headerItems.FirstOrDefault();
return !string.IsNullOrWhiteSpace(meta) ? JsonConvert.DeserializeObject<T>(meta) : default(T);
}
}
I am trying to create a webservice using the Contentservice in Apps Script and doPost(e) function to interact with Google Apps AdminDirectory service
Here is the overview of my code. I saved this as my server and published it as a websapp
function doPost(e) {
var data = e.parameter;
var resourceType = data.resourceType;
var method = data.method;
var resource = data.resource;
var resourceParams = resource.parameters;
//other code to work with AdminDIrectory
// return ContentService.createTextOutput(myoutputdata).setMimeType(ContentService.MimeType.JSON);
}
In my client code which I wrote using Apps Script to test the webservice
function test() {
var jsonData = {
authKey : 'HwZMVe3ZCGuPOhTSmdcfOqsl12345678',
resourceType : 'user',
method : 'get',
resource : {
parameters : {
userKey : 'waqar.ahmad#mydomain.com'
}
}
}
var url = 'https://script.google.com/macros/s/xyzabc12345678_wE3CQV06APje6497dyI7Hh-mQMUFM0pYDrk/exec';
var params = {
method : 'POST',
payload : jsonData
}
var resp = UrlFetchApp.fetch(url, params).getContentText();
Logger.log(resp);
}
Now when I try to read e.parameter.resource.parameters on server side, it gives error and shows that e.parameter.resource is string type.
How I can read nested objects on server side? It seems, it is recognizing only first level parameters.
Using
function doPost(e) {
return ContentService.createTextOutput(JSON.stringify(e.parameter)).setMimeType(ContentService.MimeType.JSON);
You get the response
"{"authKey":"HwZMVe3ZCGuPOhTSmdcfOqsl12345678","resource":"{parameters={userKey=waqar.ahmad#mydomain.com}}","method":"get","resourceType":"user"}"
so it looks like it is flattening any nests into a string. In the comments of a similar problem it is noted that the documentation for UrlFetchApp permits the payload to be "It can be a String, a byte array, or a JavaScript key/value map", but I assume this doesn't extend to nested key/value maps.
As noted in the other answer the solution would be to stringify the payload e.g.
var params = {
method : 'POST',
payload : {'data':JSON.stringify(jsonData)}
};
I had problems handling the payload just as a string which is why I used a key value
On the server side script you can handle with
function doPost(e) {
var data = JSON.parse(e.parameter.data);
var userKey = data.resource.parameters.userKey;
...
}
Maybe it arrives as JSON string? If that's the case you'd have to parse it back-end, something like:
resourceObj = JSON_PARSE_METHOD(e.parameter.resource);
for example in PHP this would be
$resourceObj = json_decode(e->parameter->resource);
You could find out if it's a JSON string by printing its value (or debugging it) on the backend.
Hope this helps. Cheers
I'm using MVC web Api for RESTful purpose. My controller methods return serialized Json object in string format. I've got some simple method like this:
public string Put(Folder folder)
{
var folder1 = new Folder{Id="1", IsShared=true,Name= folder.Name};
var jsSerializer = new JavaScriptSerializer();
return jsSerializer.Serialize(folder1);
}
I call Get, Put, Delete and Post methods in QUnit test like this and it works fine:
ajax: {
getData: function (url, data) {
return processRequest(url, data, "GET");
},
postData: function (url, data) {
return processRequest(url, JSON.stringify(data),"POST");
},
updateData: function (url, data) {
return processRequest(url, JSON.stringify(data),"UPDATE");
},
deleteData: function (url, data) {
return processRequest(url, JSON.stringify(data),"DELETE");
},
processRequest: function (url, data, type) {
return $.ajax({
type: type,
dataType: "json",
contentType: "application/json;charset=utf-8",
url: url,
data: data,
processData: true
});
}
},
I need to change return value from string to actual Json object because my client doesn't want serialized Json anymore. They need actual Json object. So I changed the method return type to JsonValue and parse the serialized Json object using JsonValue.Parse() method. When I trace my codes in server side, JsonValue object has proper values in its properties and looks fine but the returned JsonValue in client side has empty properties. here is changed method:
public JsonValue Put(Folder folder)
{
var folder1 = new Folder{Id="1", IsShared=true,Name= folder.Name};
var jsSerializer = new JavaScriptSerializer();
return JsonValue.Parse(jsSerializer.Serialize(folder1));
}
here is test result:
Expected:
{
"Id": "1",
"IsShared": true,
"Name": "abc"
}
Actual:
{
"Id": [],
"IsShared": [],
"Name": []
}
I appreciate any idea.
What I did to fix is adding Newtonsoft.Json.dll to my project and using Newtonsoft.Json.Linq.JToken instead of using System.Json.JsonValue. here is my method implementation:
public Newtonsoft.Json.Linq.JToken Put(Folder folder)
{
var folder1 = new Folder{Id="1", IsShared=true,Name = folder.Name};
var jsSerializer = new JavaScriptSerializer();
return Newtonsoft.Json.Linq.JObject.Parse(jsSerializer.Serialize(folder1));
}
and if you have an array of JSON, you need to parse like this:
public Newtonsoft.Json.Linq.JToken Put(IList<Folder> folders)
{
var folder1 = new Folder{Id="1", IsShared=true,Name = folder.Name};
var jsSerializer = new JavaScriptSerializer();
return Newtonsoft.Json.Linq.JArray.Parse(jsSerializer.Serialize(folders));
}
Anyone knows how to send the request using JSON content in windowsphone. I had the JSON parameters how to post it.
Simply serialize the data in JSON, and write it as a POST request to the server. Here's how I do it in one of my apps:
private static IObservable<T> GetDataAsync<T, TRequest>(TRequest input, string address)
{
var request = HttpWebRequest.Create(address);
request.Method = "POST";
var getRequestStream = Observable.FromAsyncPattern<Stream>(
request.BeginGetRequestStream,
request.EndGetRequestStream);
var getResponse = Observable.FromAsyncPattern<WebResponse>(
request.BeginGetResponse,
request.EndGetResponse);
return getRequestStream()
.SelectMany(stream =>
{
try
{
using (var writer = new StreamWriter(stream))
writer.WriteLine(JsonConvert.SerializeObject(input));
}
catch
{
// Intentionally ignored.
}
return getResponse();
})
.Select(webResponse =>
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
return JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
});
}