Insert JSON from URL string - c#

I have created a REST web service that should get a JSON string and convert it to an object in C#. I have created my classes and used the deserialization:
RootObject test = JsonConvert.DeserializeObject<RootObject>("id");
So far so good, I need to call my function :
public string JSONData(string id)
Is there a way to insert my JSON in the URL so I can trigger my function, or am I missing something fundamental?
http://localhost/RestSrv/Json/....
What should I put in the ... that will give value to my id string and call my JSONData function that will deserialize the JSON after? Should I use an online JSON convert to URL tool?

I can think of two ways to do this
Send JSON via HTTP POST with Content-Type: application/json header
Send HTTP Query String with the required data. For example
?object[type]=person&children_names[]=Mia&children_names[]=Anna
Would convert to JSON (https://www.convertonline.io/convert/query-string-to-json)
{"object":{"type":"person"},"children_names":["Mia","Anna"]}
Option 1 is better since URL string can be long and have a length limitation.

Related

C# .Net API Post Call Using HttpResponseMessage Post([FromBody] is always null

I'm new to writing .net APIs and I'm working in Visual Studio 2017. I've been working on this for a couple of days and I'm completely stumped. I'm trying to create a simple web API that a Post call sends a cXML string passed into it via the Post Body. I then take the incoming cXML string and simply save it to a text file on a network drive. That is all I need to do, I don't need to de-serialize the xml, read any of the fields or extract any data out of the XML, I just need to grab the entire input xml string and save it to a text file. The problem I'm having is no matter what I've tried the incoming body always seems to be null. My code is simple:
[HttpPost]
[Route("api/Pass_XML_to_File")]
public HttpResponseMessage Post([FromBody] dynamic IncomingXML)
{
//do work here: take Incoming xml string and save it to a file which should be simple...
}
Unfortunately my IncomingXML variable is always null, so I have no data to save into a text file. I've been testing this from Postman and no matter what I've tried the variable is always null.
I've tried many other ways such as
Post([FromBody] XmlDocument IncomingXML)
Post([FromBody] string IncomingXML), etc.
I've tried changing in Content-Type header in Postman from application/xml, text/xml, text and a few others without any success. The funny thing is if I pass a JSON string in the body (changing the Content-Type to text/JSON) the data comes in perfectly without issue. Just when I pass xml the incoming body is always null.
Does anyone know how I can get the body xml to come in as a string so I can simply save it to a text file for later processing on a separate system? Thank you all in advance for your assistance.
Can you post the form you sent on the client side?
[HttpPost]
[Route("api/Pass_XML_to_File")]
public HttpResponseMessage Post([FromBody] dynamic IncomingXML)
{
// data is coming in correctly.
return null;
}
Postman Client Send :
{
"IncomingXML":"<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don'tforgetmethisweekend!</body></note>"
}
data comes to variable successfully.
if you want to accept a xml format request, you should do the below steps:
Startup.ConfigureServices edit:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddXmlSerializerFormatters();
}
Apply the Consumes attribute to controller classes or action methods that should expect XML in the request body.
[HttpPost]
[Route("api/Pass_XML_to_File")]
[Consumes("application/xml")]
public HttpResponseMessage Post([FromBody] dynamic IncomingXML)
{
// data is coming in correctly.
return null;
}
Note: Install the Microsoft.AspNetCore.Mvc.Formatters.Xml NuGet package.

Processing Post Request from Slack

I've setup an asp.net MVC web application to capture post request. I've set breakpoints to see what info is coming through. When an interactive button is clicked, my breakpoint is hit but the object has no details. It simply says {Object} when i hover over value. When I use Postman and send a raw JSON body, it displays the JSON. May I ask how am i suppose to process the slack object that is sent?
public void Post(object value)
{
// breakpoint here
}
For interactive messages Slack send a standard POST request with a single form-data encoded parameter called payload in the body. This parameter contains the data of the actual request as JSON string.
You can simulate this with Postman by using the following parameters:
Request type: POST
Header: Content-Type: application/x-www-form-urlencoded
Body: form-data, with key=payload and value = JSON string.
So the body is not fully JSON as you assumed, but contains a form parameter with a JSON encoded string. If you change your app accordingly, it will work.
In c# you can access the content of the payload parameter with Request["payload"] (see this answer or details).
Then you still need to decode the JSON string into an object of course. An easy approach is to use JavaScriptSerializer.Deserialize. (see this answer for details and alternative approaches).

ServiceStack request POST body as query string

I am trying to implement an IPN handler in C# and I am using ServiceStack as my backend framework. I am facing the following issue however;
I am trying to find a way to take the POST body of a request as a querystring but I fail to do so. I am using IRequest.GetRawBody(); but the POST data are returned in a formatted way to make it readable.
Is there any way to easily take the POST body as a querystring? I want something similar to PHP's $_POST so I can ecrypt the data with HMAC SHA256 but I can find a way to do it without writing a helper class with hardcoded details about the POST request body. I've tried searching online and ServiceStack's documentation but I did not find anything useful.
Any help will be very appreciated, thanks in advance!
The QueryString is on the URL not the Request Body. If you just want access to the raw Request body that's posted you can have your Request DTO implement IRequiresRequestStream which tells ServiceStack to skip deserializing the body so you can deserialize it yourself, e.g:
public class MyRequest : IRequiresRequestStream
{
public Stream RequestStream { get; set; }
}
public class MyServices : Service
{
public object Any(MyRequest request)
{
var bytes = request.RequestStream.ReadFully();
var text = bytes.FromUtf8Bytes();
...
}
}

ASP.NET Web Api - the framework is not converting JSON to object when using Chunked Transfer Encoding

I have an http client in Android sending HTTP PUT requests to a REST api implemented with C# and ASP.NET WebApi framework.
The framework should be able to magically convert (deserialize) the JSON into a model class (plain object) as long as the JSON fields match the properties in the C# class.
The problem comes when the http requests come with Chunked Transfer Encoding that makes the Content-Length = 0 (as per http://en.wikipedia.org/wiki/Chunked_transfer_encoding) and the framework is not able to map the JSON that's within the Http request message so the parameter is null.
See this simple example:
[HttpPut]
public HttpStatusCode SendData(int id, int count, [FromBody]MyData records, HttpRequestMessage requestMessage)
{
var content = requestMessage.Content;
string jsonContent = content.ReadAsStringAsync().Result; //this gets proper JSON
return HttpStatusCode.OK;
}
The problem is that records is null when the client sends the http request chunked.
As I understand, the Chunked Transfer encoding is simply a transfer property that the http client or server should not have to worry about at the application layer (transport layer's business). But it seems the framework doesn't manage it as I'd like.
I could manually retrieve the JSON from the HttpRequestMessage and de-serialize it into a MyData object, but I wouldn't be able to take advantage of the ASP.NET framework's magic. And you know the rule: the more code you add the more bugs you are likely to introduce.
Is there any way to handle Http Put requests with JSON that come as chunked transfer encoded in ASP.NET Web Api 2?
EDIT: This is the model class for this example that the framework should instantiate when de-serializing the JSON
public class MyData
{
public string NamePerson {get; set;}
public int Age {get; set;}
public string Color {get; set;}
}
I recently stumbled upon the the same issue, and managed to create a workaround for it. I took the original JsonMediaTypeFormatter class, subclassed it and updated the implementation of the ReadFromStreamAsync/ReadFromStream-method.
https://gist.github.com/cobysy/578302d0f4f5b895f459
Hope this helps.

RESTful web service returning XML not JSON

I have this simple web service, right now it just looks to see if the part number is A123456789 and then it returns a model number. This will be replaced by logic that will be connecting into a database to check the partno against and then return the actual model number. But at this point I just need it to return some dummy JSON data. However when I use Fiddler and look at the call in the web broswer of http://localhost:PORT/Scan/Model/A123456789 it returns this
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Model: CVS-1679</string>
But when I do a GET in fiddler of the same URI I get
"Model: CVS-1679"
Only under the textview tab.
Why is it being returned in XML (in the browser and text in Fiddler) and not JSON, when I have setup my ResponseFormat to be JSON?
My Code:
[WebGet(UriTemplate = "Model/{partno}", ResponseFormat = WebMessageFormat.Json)]
public string Model(string partno)
{
if (partno == "A123456789")
{
string modelno = "CVS-1679";
return "Model: " + modelno;
}
else
{
string modelno = "CVS-1601";
return "Model: " + modelno;
}
}
ASP.NET webservice return XML / SOAP message by default. In case you want to return Json string, you would need to decorate the Webservice with [ScriptService] attribute. This inform the IIS that this service would be used by ASP.NET AJAX calls. These attribute are part of System.Web.Extensions.
You can define the web method response format by decorating the webmethod with ScriptMethod attribute.
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
However even after decorating the webservice and webmethod by these attribute, the response can still be in XML format. This behaviour happen when the client which makes the request does not set the Request Header content type as “application/json”.
Before return the method call from webmethod serialize to Json string using JavaScriptSerializer
Debugging WebService using Fiddler
It is quite easy to use fiddler to test webservice. Following figure is an example of how to call a Webservice which returns a json string. Note that the request content type is set to application/json. The parameters expected by webserivce is mentioed in the Request Body section.
Note that the request content type is set to application/json.
It is being returned in Json if you look at the format of the data you get...
key: value
or in your case
string Model = "CVS-1679"
When you view it in fiddler your seeing the raw serialization transport from one MS endpoint to the other. The serialisation & De-serialisation elements in the .NET framework take care of transporting it across the wire, so that when you get the object back into your .NET app at the calling end, you get a variable called Model with the value you expect.
If you try to send an entire class you'll see a lot of nested XML tags, but when you get the object in your code, you'll see a first class citizen in the object hierarchy.
The reason it appears in your browser is because, the browser doesn't know how to de-serialise it, and so just displays the text

Categories