NetCore 3.1 HttpResponseMessage Post([FromBody] return custom XML response - api

I'm new to creating API's and I'm using Visual Studio 2019. I'm trying to write a simple API that our customer passes XML to us, I save the XML to a file for later processing and return back to the customer a custom XML response that they require. I created a .NetCore 3.1 Microsoft.AspNetCore.Mvc API. The code is simple:
[HttpPost]
[Route("api/Pass_XML_to_BOOMI")]
[Consumes("application/xml")]
public HttpResponseMessage Post([FromBody] XmlDocument IncomingXML)
{
XmlDocument incomingXML = new XmlDocument();
XmlDocument outgoingXML = new XmlDocument();
String payLoadID = Guid.NewGuid().ToString();
String curDate = System.DateTime.Now.ToString();
string INBOUND = IncomingXML.OuterXml.ToString();
string xmlresponse = #"<?xml version=""1.0"" encoding=""UTF-8""?><!DOCTYPE cXML SYSTEM ""http://xml.cXML.org/schemas/cXML/1.1.009/cXML.dtd"">
<cXML payloadID=""" + payLoadID + #""" xml:lang=""en-US"" timestamp=""" + curDate + #"""><Response>
<Status code=""200"" text=""OK""/></Response></cXML>";
outgoingXML.LoadXml(xmlresponse);
//grab order ID number and save to file
string ID = "";
XmlElement element = IncomingXML.SelectSingleNode("cXML/Request/OrderRequest/OrderRequestHeader") as XmlElement;
if (element != null)
{
ID = element.GetAttribute("orderID");
}
string filename = #"f:\" + ID + ".xml";
System.IO.File.WriteAllText(filename, INBOUND);
// Create the response
var response_back = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(outgoingXML.InnerXml, Encoding.UTF8),
};
return response_back;
}
The problem I'm having is when I pass the XML in through Postman all works fine and my file is created but no matter what I try the response back is missing my custom XML (it seems be completely ignoring my Content =) and it is in JSON format, not XML.
Here is how the response comes back in Postman:
{
"version": {
"major": 1,
"minor": 1,
"build": -1,
"revision": -1,
"majorRevision": -1,
"minorRevision": -1
},
"content": {
"headers": [
{
"key": "Content-Type",
"value": [
"text/plain; charset=utf-8"
]
}
]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"trailingHeaders": [],
"requestMessage": null,
"isSuccessStatusCode": true
}
I need to somehow send back an XML response with my custom XML:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE cXML SYSTEM "http://xml.cXML.org/schemas/cXML/1.1.009/cXML.dtd">
<cXML payloadID="83dbfb00-22cc-4cb9-9e6b-f34b47f3cbcd" xml:lang="en-US" timestamp="4/2/2022 12:18:49"><Response>
<Status code="200" text="OK"/></Response></cXML>
Does anyone have any idea what I'm doing wrong and how I can accomplish this? Thank you all in advance.

Related

json path for response - API Restassured

Below is the response i get for post call.
How to get quoteId and fee amount value using Json from the below response.
{
"data": {
"quoteId": "Lid123",
"loanTerm": "48.0",
"lenderRate": "4.5",
"customerRate": "4.499999999999904",
"fees": [
{
"feeType": "EstablishmentFee",
"feeAmount": "450"
}
],
"periodPaymentInclGSTAmount": "6416.5"
}
}
Thank you in advance
You can use jsonpath() method to extract value from json.
Response res = ...
String quoteId = res.jsonPath().getString("data.quoteId");
String feeAmount = res.jsonPath().getString("data.fees[0].feeAmount");
System.out.println(quoteId); //Lid123
System.out.println(feeAmount); //450
String id = JsonPath.from(reponseBody).getString("data.quoteId");
String EstablishmentFee = JsonPath.from(reponseBody).getString("data.fees.feeAmount");

How to deserialize the GraphQL server response to object?

How to convert the GraphQL response to object on the client?
I do this way:
var request = new GraphQLRequest
{
Query = #"{customer(id:4){id,firstName,lastName,contact,email}}"
};
var jsonSerializer = new njs.NewtonsoftJsonSerializer();
using var graphQLClient = new GraphQLHttpClient("https://localhost:5011/graphql/", jsonSerializer);
//var response = await graphQLClient.SendQueryAsync<Customer>(request);
var response = await graphQLClient.SendQueryAsync<dynamic>(request);
var graphQLQueryType = #"customer";
var cust = response;//.Data..customer;
var stringResult = response.Data.ToString();
var resultzzz = JsonConvert.DeserializeObject<List<Customer>>(stringResult);
and the result as a string is:
stringResult = "{\r\n "customer": {\r\n "id": "4",\r\n "firstName": "Name#4",\r\n "lastName": "LastName#4",\r\n "contact": "Contact#4",\r\n "email": "you#4#mai.com"\r\n }\r\n}"
It is ok.
But I need to deserialize this response to object class Customer.
and this
var resultzzz = JsonConvert.DeserializeObject(stringResult);
gives me:
ex = {"Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List1[GraphQL.Client.Example.Customer]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error eith...
`
What I do wrong? How to fix it?

Can anyone help me out with block.io API for withdrawal of bitcoin from wallet?

I am trying to use block.io API, before few months I tried and implemented, it was working perfect, and now they have changed signed signature method, All APIs working correct, only withdrawal API not working, Response of curl is showing success, but says required more_signatures_needed , I don't know how to do this, Can anyone help me? I will be thankful.
protected void Page_Load(object sender, EventArgs e)
{
myPage.Text = readHtmlPage("https://block.io/api/v2/withdraw_from_addresses/");
//fecth response
String myUri = Session["myPagecc"].ToString();
//display response
Label1.Text = myUri.ToString();
}
private String readHtmlPage(string url)
{
String api_key = "myapikey";
double amounts = "btcamount";
String to_addresses = "receiveraddress";
string FROM_ADDRESS = "myaddress";
string NEWCODE = Guid.NewGuid().ToString().Substring(0, 5);
string priority="medium";
String result = "";
String strPost = "api_key=" + api_key + "&from_addresses=" + FROM_ADDRESS + "&to_addresses="+to_addresses +"&amounts="+amounts+"&priority="+priority+"&nonce="+NEWCODE;
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally
{
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
return result;
}
"status" : "success", "data" : { "reference_id" : "70ab0922cf036481533e7f345068c0bed36f9681d644d8", "more_signatures_needed" : true, "inputs" : [ { "input_no" : 0, "signatures_needed" : 1, "data_to_sign" : "3916022666e29882298d54c2c8f2ab3306cc4e774594f5db9", "signers" : [ { "signer_address" : "jhE397dsNaNLByJ8WV43emD1mhSpPtwDV", "signer_public_key" : "a34b48a3a18373020d8d96fb53b733d373cd3ba9b5bbfd2c9f8105c8939058130d", "signed_data" : null } ] } ], "encrypted_passphrase" : { "signer_address" : "NaNLmhSByJ8WV43emD1jhE397dspPtwDV", "signer_public_key" : "373cd3ba9b5bbfd2c9f8020d8d96fb53b733d373a34b48a3a18105c8939058130d", "passphrase" : "r20/Wyy5iTVFmpcmn1Y8JOMR8mP7jAqaBrMf2UOW2aEBQSQ1XfxpgonIyFLDOKkmuqH84sETSjXTFsl3dpo5niABB2rL69vnsLbS4DaXMw1o33NH0zgHyzdkAYmIoeGe85YVPMkrQsNhLrGQ6JUaubT+W3rIBxP7rCqYznnMnt8QxG4wu5LSh2EY8fja6AI1" }, "unsigned_tx_hex" : "010000000127d8d4654bc8cf69c9b1980c1afa67e51b5b28241ac080100000023220020200d0c2118ad382e8dab4f3c2ddf5ab8ca1d8ac3ffa3d910a0a2aa86cb69cb77bb62e2a7f12fbc8a699ffffffff076a914103ee4139219756a503842b0ad01000000000019caf5a381440b66bd81188ac64a401000000000017a9145af1577250a83928e306b35f8463047d72d9e3408700000000" } }
Any solution for this please.
With Block.IO token withdrawal it seems we need to send some extra secure pins
as per their doc: https://block.io/api/simple/signing
Like to know how to send cURL to execute ?
Their sample cURL is not working: /api/v2/withdraw_from_addresses/?api_key=API KEY&from_addresses=ADDRESS1,ADDRESS2,...&to_addresses=ADDRESS1,ADDRESS2,...&amounts=AMOUNT1,AMOUNT2,...
response is:
{[status, success]}
{[data, {
"reference_id": "24fe5a.....",
"more_signatures_needed": true,
"inputs": [
{
"input_no": 0,
"signatures_needed": 1,
"data_to_sign": "2498d....",
"signers": [
{
"signer_address": "1H4.....",
"signer_public_key": "037710.....",
"signed_data": null
}
]
}
],
"encrypted_passphrase": {
"signer_address": "1H4...",
"signer_public_key": "0377....",
"passphrase": "fDCM0...."
},
"unsigned_tx_hex": "01000...."
}]}
if possible: expecting some sample in asp.net vb please

How do you access the NFL's API's?

I've been trying to access or find away to access data from NFL.com, but have not found it yet. There is public documentation on these sites:
https://api.nfl.com/docs/identity/oauth2/index.html
but these docs do not tell you how to get a client id or client secret.
I've also tried:
http://api.fantasy.nfl.com/v2/docs
The documentation says that you need to send an email to fantasy.football#nfl.com to get the app key. I sent an email a while ago and a follow up and I've received no responses.
You can send requests to these API's and they will respond telling you that you have invalid credentials.
Have you had any success with this? Am I doing something wrong? Are these sites out of date?
EDIT: I emailed them on 10/30/2015
While I haven't had any success with api.nfl.com, I am able to get some data from the api.fantasy.nfl.com. You should have read access to all of the /players/* endpoints (e.g. http://api.fantasy.nfl.com/v1/players/stats?statType=seasonStats&season=2010&week=1&format=json). I would think you need an auth token for the league endpoints and the write endpoints.
How long ago did you email them?
EDIT:
I emailed the NFL and this is what they had to say: "We've passed your API request along to our product and strategy teams. NFL.com Fantasy APIs are available on a per-use, case-by- case basis for NFL partners. Our team reviews other requests, but our APIs are typically not available for external usage otherwise."
You can replicate the experience of generating a client JWT token in Nfl.com by opening chrome inspector and going to nfl.com then clearing your application local storage and your network console, refreshing the page and then just watching the responses come across the line and how it issues a token.
I'd argue they probably have a bit of a security gap in how they issue tokens because they sent their clientId and clientSecret to the end user which is later posted back to the server create a JWT, when they should probably have some sort of end point that gens a token and also has some site origin protections, but hey makes consumption of the API a bit easier.
Usage:
using (var client = await WebClientFactory.Create())
{
foreach (var week in all)
{
var url = $"https://api.nfl.com/football/v1/games?season={year}&seasonType=REG&week={week}&withExternalIds=true";
var content = await client.DownloadStringTaskAsync(url);
var obj = JsonConvert.DeserializeObject<SeasonStripV2>(content);
// do so0mething here
}
}
The meat and potatoes:
public class WebClientFactory
{
static WebClientFactory()
{
ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) =>
{
Console.WriteLine(er);
// I had some cert troubles you may need to fiddle with this if you get a 405
// if (c.Subject?.Trim() == "CN=clubsweb.san1.nfl.com")
// {
// return true;
// }
Console.WriteLine(c);
return false;
};
}
public static async Task<WebClient> Create()
{
var clientInfo = new
{
clientId = "e535c7c0-817f-4776-8990-56556f8b1928",
clientKey = "4cFUW6DmwJpzT9L7LrG3qRAcABG5s04g",
clientSecret = "CZuvCL49d9OwfGsR",
deviceId = "1259aca6-3793-4391-9dc3-2c4b4c96abc5",
useRefreshToken = false
};
var clientUploadInfo = JsonConvert.SerializeObject(clientInfo);
var webRequest = WebRequest.CreateHttp("https://api.nfl.com/identity/v1/token/client");
webRequest.Accept = "*/*";
webRequest.ContentType = "application/json";
webRequest.Method = WebRequestMethods.Http.Post;
await WriteBody(webRequest, clientUploadInfo);
var result = await GetResult(webRequest);
var tokenWrapper = JsonConvert.DeserializeObject<RootV2>(result);
var client = new WebClient();
client.Headers.Add("Authorization", $"Bearer {tokenWrapper.accessToken}");
return client;
}
private static async Task WriteBody(HttpWebRequest webRequest, string clientUploadInfo)
{
using (var stream = webRequest.GetRequestStream())
{
using (var sw = new StreamWriter(stream))
{
await sw.WriteAsync(clientUploadInfo);
}
}
}
private static async Task<string> GetResult(HttpWebRequest webRequest)
{
using (var response = await webRequest.GetResponseAsync())
{
return await GetResult((HttpWebResponse) response);
}
}
private static async Task<string> GetResult(HttpWebResponse webResponse)
{
using (var stream = webResponse.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream))
{
return await sr.ReadToEndAsync();
}
}
}
private class RootV2
{
public string accessToken { get; set; }
public int expiresIn { get; set; }
public object refreshToken { get; set; }
}
}
Note you can also getting a token by calling this endpoint:
POST "https://api.nfl.com/v1/reroute"
BODY: "device_id=5cb798ec-82fc-4ba0-8055-35aad432c492&grant_type=client_credentials"
and add these headers:
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
client.Headers["X-Domain-Id"] = "100";
Hooks Data provides a real-time API for major US sports including NFL.
1) Get API KEY here: https://www.hooksdata.io/signup?invite=SM4555
2) Subscribe to soccer games:
curl -H "Content-type: application/json" -d '{
"query": "SELECT * FROM NFLGames WHERE away_team.team_name = 'New England Patriots' OR home_team.team_name = 'New England Patriots' AND start_datetime.countdown = 3600"}' 'http://api.hooksdata.io/v1/subscriptions'
DOCS: https://www.hooksdata.io/docs/api/datasources/nflgames/
3) Optional: Add a Webhooks URL where you want to get the data: https://www.hooksdata.io/webhooks
4) Pull the data using fetch endpoint https://www.hooksdata.io/docs/api/api-reference/#query-datasource
5) Get all the data in JSON:
{
"matches_count": 1,
"results": [
{
"_entity_type": "NFLGame",
"_id": "NFLGame_400999173",
"away_score": null,
"away_team": {
"_entity_type": "NFLTeam",
"_id": "NFLTeam_NE",
"acronym": "NE",
"division": "AFC East",
"id": "NFLTeam_NE",
"team_name": "New England Patriots"
},
"game_id": "400999173",
"home_score": null,
"home_team": {
"_entity_type": "NFLTeam",
"_id": "NFLTeam_PHI",
"acronym": "PHI",
"division": "NFC East",
"id": "NFLTeam_PHI",
"team_name": "Philadelphia Eagles"
},
"link": "http://espn.go.com/nfl/game?gameId=400999173",
"start_datetime": null,
"status": "FUTURE"
}
]
}

How can I use a payload instead of form-data for log4javascript

I am bound to the restrictions of my webservice: It expects a json-payload!
So, doing something like
var ajaxAppender = new log4javascript.AjaxAppender("clientLogger");
var jsonLayout = new log4javascript.JsonLayout();
ajaxAppender.setLayout(jsonLayout);
log.addAppender(ajaxAppender);
won't work, as it creates two keys in the forms-collection (data and layout).
How can I, with built-in options, get a json-payload?
I've created a JsonAppender
function JsonAppender(url) {
var isSupported = true;
var successCallback = function(data, textStatus, jqXHR) { return; };
if (!url) {
isSupported = false;
}
this.setSuccessCallback = function(successCallbackParam) {
successCallback = successCallbackParam;
};
this.append = function (loggingEvent) {
if (!isSupported) {
return;
}
$.post(url, {
'logger': loggingEvent.logger.name,
'timestamp': loggingEvent.timeStampInMilliseconds,
'level': loggingEvent.level.name,
'url': window.location.href,
'message': loggingEvent.getCombinedMessages(),
'exception': loggingEvent.getThrowableStrRep()
}, successCallback, 'json');
};
}
JsonAppender.prototype = new log4javascript.Appender();
JsonAppender.prototype.toString = function() {
return 'JsonAppender';
};
log4javascript.JsonAppender = JsonAppender;
used like so
var logger = log4javascript.getLogger('clientLogger');
var jsonAppender = new JsonAppender(url);
logger.addAppender(jsonAppender);
According to log4javascript's change log, with version 1.4.5, there is no longer the need to write a custom appender, if the details sent by Log4Javascript suffice.
1.4.5 (20/2/2013)
- Changed AjaxAppender to send raw data rather than URL-encoded form data when
content-type is not "application/x-www-form-urlencoded"
https://github.com/DECK36/log4javascript/blob/master/changelog.txt
Simply adding the 'Content-Type' header to the AjaxAppender and setting it to 'application/json' is enough
ajaxAppender.addHeader("Content-Type", "application/json;charset=utf-8");
A quick test using fiddler shows that log4javascipt sends a collection of objects. Here's a sample of the payload:
[{
"logger": "myLogger",
"timestamp": 1441881152618,
"level": "DEBUG",
"url": "http://localhost:5117/Test.Html",
"message": "Testing message"
}]