How to stop ASP .NET from JSONifying JSON - asp.net

I am currently trying to wrap an internal API and make it external. To do so, I am trying to relay the JSON responses from the internal API and send that exact response when someone makes a get request. Instead, ASP .NET is JSONifying that son and adding extra back slashes as escape characters (when in fact those slashes are really escape slashes put in by the internal api).
How can i get it so asp does not jsonify the string

You can write your json data directly to response and set right content headers.
public HttpResponseMessage GetData()
{
var json = "\"value\": \"da\\ta\"";
var resp = Request.CreateResponse(HttpStatusCode.OK);
resp.Content = new StringContent(json);
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
resp.Content.Headers.ContentEncoding = //your json encoding, you can get it from response inner API
return resp;
}

Related

OAuth2 endpoint post request Xero

First up, I'm not using the Xero api. This is more an OAuth2 questions than Xero specifically I think.
Not quite sure if the issue is a general OAuth2 problem or a Xero implementation of OAuth2. I can successfully authenticate, get my tokens etc from Xero. I can even make successful Get requests to their endpoints for Invoices and contacts. My problem is trying to POST anything, i.e. create an invoice.
The server responds with, 400 Bad request. I've confirmed by actual post data is correct by putting the XML into their API tester and all is good there.
Shouldn't a post request be a standard httpwebequest, (POST) with the query string ?oauth_signature=[sig here], and the actual post data URL encoded and sent via stream? Is my implementation correct and should I be looking elsewhere for the problem? Is the data sent in the form supposed to be included in the signature?
{
byte[] reqData = encode.GetBytes(postData);
HttpWebRequest request = WebRequest.CreateHttp(url + querystring) as HttpWebRequest;
request.Method = "POST";
try {
using (Stream stream = request.GetRequestStream) {
stream.Write(reqData, 0, reqData.Length);
}
using (HttpWebResponse response = request.GetResponse) {
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
dynamic responseFromServer = reader.ReadToEnd();
return responseFromServer;
}
} catch (Exception ex) {
}
}
Xero uses OAuth1.0a, rather than OAuth2. The OAuth signature needs to be supplied as a header rather than a query string. I believe it should be exactly the same as the successful GET requests you're making.
https://oauth.net/core/1.0a/#rfc.section.5.4.1:
The OAuth Protocol Parameters are sent in the Authorization header the following way:
Parameter names and values are encoded per Parameter Encoding.
For each parameter, the name is immediately followed by an '=' character (ASCII code 61), a '"' character (ASCII code 34), the parameter value (MAY be empty), and another '"' character (ASCII code 34).
Parameters are separated by a comma character (ASCII code 44) and OPTIONAL linear whitespace per [RFC2617].
The OPTIONAL realm parameter is added and interpreted per [RFC2617], section 1.2.
Update for those finding this now, Xero API now has OAuth2 in public Beta
https://developer.xero.com/documentation/oauth2/overview

How can I catch a pound sign(#) from URL with multiple values in ASHX files

This is my ASHX File where I am catching multiple parameters from request URL using httpcontext, and it is working properly but when I am including a Hash(#) value in Text parameter through the URL. It is not taking the value of FLOW which is another parameter(next to Text parameter).
So it is working for:
http://localhost:10326/ussd.ashx?user=MSL&pass=MSL663055&tid=65506&msisdn=8801520101525&text=***3333**&flow=begin&momt=mo
And it is not working for:
http://localhost:10326/ussd.ashx?user=MSL&pass=MSL663055&tid=65506&msisdn=8801520101525&text=***3333#**&flow=begin&momt=mo
My ASHX files:
public void ProcessRequest(HttpContext context)
{
HttpRequest httpRequest = context.Request;
string user = httpRequest.QueryString["user"].ToString();
string pass = httpRequest.QueryString["pass"].ToString();
string tid = httpRequest.QueryString["tid"].ToString();
string msisdn = httpRequest.QueryString["msisdn"].ToString();
string text = httpRequest.QueryString["text"].ToString();
flow = httpRequest.QueryString["flow"].ToString();
HttpContext.Current.Session["user"] = user;
HttpContext.Current.Session["pass"] = pass;
HttpContext.Current.Session["tid"] = tid;
HttpContext.Current.Session["msisdn"] = msisdn;
HttpContext.Current.Session["text"] = text;
HttpContext.Current.Session["flow"] = flow;
You need to URI encode your parameter values before they are added to the URL. This way the server will not get confused by unsafe characters such as '#' which has its own meaning when included as part of a URL. See RFC 3986 Section 2.
See Encode URL in JavaScript as an example of how to encode the sent data using JavaScript. Whatever is sending the data in the URL will need to do the encoding. There is not much you can do once the request has reached the server. Without knowing how your URL is being created, I can't offer much more.
In short: the problem is with your client code not your ASHX file.

web api (asp.net) - sending data via post method

I'm trying to pass data via post method from my client to a server.
I'm using WebApi to do so.
This i the code i used:
client:
var client = new RestClient();
client.EndPoint = #"http://localhost:57363/hello";
client.Method = HttpVerb.POST;
client.PostData = "{value: Hello}";
var json = client.MakeRequest();
Console.WriteLine(json);
Console.Read();
server:
// POST api/<controller>
public string Post([FromBody]string value)
{
return value + ", world.";
}
The server responds as expected when using postman. However, the client passes a null value instead of the real value.
What am i doing wrong?
First of all a correct json would look like "{value: 'Hello'}".
I use json-online to easily validate such inline json.
On the other hand, I think that you should send just the value in this case, not the entire json (because you are trying to resolve a simple type,a string), so the client should send a request like:
client.PostData = "'Hello'";

How to do an API call in ASP.NET (VB)

I want to make an API call where the response is in XML format.
This is the API description: http://www.dictionaryapi.com/products/api-collegiate-dictionary.htm
I have registered and I have a key to use in the request URL.
Could anyone give me an idea of how to make the call and analyse the response?
Thankyou.
Something along the lines of:
var request = WebRequest.Create("http://www.dictionaryapi.com/api/v1/references/collegiate/xml/hypocrite?key=1234");
var response = request.GetResponse();
var xdoc = XDocument.Load(response.GetResponseStream());
Then you can grab what you need like:
xdoc.Element("ElementName");

How do I set the response format to the same format as the request?

I created a custom dispatcher to handle versioning that uses a customer media type. It looks something like this:
application/vnd.mycompany.myapi-v1+json
The extraction of the version number in order to select the correct controller is all up and working, but being new to MVC, I am not sure how to set the response format. What we want to do is set the response format to match the request. So in this example, the response will be in json. Now I assume I'm going to have to extract that from this content type as well which is fine, but could someone give me an example of how i set the response format of this request in MVC4 assuming I have already created the method which will extract the format as a string?
private string GetResponseFormat(){
//some shennanigans here
}
P.S. the reason for not having the client use the accept header during the request is that there are already clients out there that are using our old service which would set the accept header to match the request.
You can also use Content method to return custom response type:
string responseType = GetResponseFormat();
...
switch(responseType){
case "json":
string json = "yourJSON";
return Content(json, "application/json");
case "xml":
string xml = "yourXML";
return Content(xml, "text/xml");
default:
string plaintxt = "yourPlaintext";
return Content(plaintxt, "text/plain"):
}
I was able to clear the existing Accept header and add to it:
private void SetResponseFormatToRequestFormat(HttpRequestMessage request)
{
// figure out what the request format was
_contentTypeHeader = request.Content.Headers.ContentType.ToString();
if(_contentTypeHeader.Contains("xml")) _contentType = "application/xml";
if (_contentTypeHeader.Contains("json")) _contentType = "application/json";
// set response format to the same as the request format
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(_contentType));
}

Resources