Can't see the JSON result of a Get request in postman and shows empty string array - json

I have an ASP.NET CORE application that sends a POST/GET request to a REST (Orthanc Rest API). The issue is I receive the result and convert it to a JSON, but postman shows as an empty array. here is my code:
// GET Method
public class PACSController : ControllerBase
{
// GET: api/PACS
[HttpGet]
public async Task<object> Get()
{
var result = await Orthanc.Orthanc.InstanceAsync();
return result;
}
}
public class Orthanc
{
public static string baseUrl = "https://demo.orthanc-server.com/";
public static async Task<object> InstanceAsync()
{
string url = baseUrl + "instances";
using (HttpClient client = new HttpClient())
using (HttpResponseMessage res = await client.GetAsync(url))
using (HttpContent content = res.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
Console.WriteLine(data);
}
var jData = JsonConvert.DeserializeObject(new string[] { data }[0]);
return jData;
}
}
}
The result of request inside the code
Postman result

As part of the work to improve the ASP.NET Core shared framework, Newtonsoft.Json has been removed from the ASP.NET Core shared framework for asp.net core 3.x.
Follow the steps:
Install the Microsoft.AspNetCore.Mvc.NewtonsoftJson package on nuget.
Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson
Update Startup.ConfigureServices to call AddNewtonsoftJson.
services.AddControllersWithViews().AddNewtonsoftJson();
Reference:
https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio#use-newtonsoftjson-in-an-aspnet-core-30-mvc-project

Related

get Json Data From URL in C#

I am new to json i want get json data from a link, here from web search i have written code
private void button1_Click(object sender, EventArgs e)
{
string url = #"http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/web/WFS/inSPIRED-inTRONICS_Business-Site/en_US/-/USD/ViewProduct-Start?SKU=1599925&CategoryName=151&CatalogID=Computers";
using (WebClient wc=new WebClient())
{
json = wc.DownloadString(url);
}
string path = #"ouptputfileJSON.json";
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(json);
}
}
}
When i execute this code i'm getting output in html page. how to get in json data of select product in the link provided
Here is the rest endpoint you are looking for:
http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/rest/WFS/inSPIRED-
inTRONICS_Business-Site/-;loc=en_US;cur=USD/products/1599925
Documentation about other rest endpoints:
https://support.intershop.com/kb/index.php/Display/T27711
Because
http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/web/WFS/inSPIRED-inTRONICS_Business-Site/en_US/-/USD/ViewProduct-Start?SKU=1599925&CategoryName=151&CatalogID=Computers
Is webpage and not API endpoint so you need to find proper endpoint from where you want to get data
Once you get Proper Endpoint you can use below
Here is an example how you can use httpclient to make a request
static void Main()
{
Task t = new Task(DownloadPageAsync);
t.Start();
Console.WriteLine("Downloading page...");
Console.ReadLine();
}
static async void DownloadPageAsync()
{
// ... Endpoint
string page = "request URL";
// ... Use HttpClient.
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
// ... Read the string.
string result = await content.ReadAsStringAsync();
Console.WriteLine(result);
}
}

How to send serializable request object with httpClient in .net core?

I'm new in .net and I'm looking for a way (if exists) to be able to pass a request object to a http client without "manually" serialize it to json. I did some java implementations in the past and there it was done under the hood and I thought that it should be possible also in .netCore
This is the request object:
public class Request
{
[JsonProperty("number", NullValueHandling = NullValueHandling.Ignore)]
public int Number { get; set; }
}
and I'm looking for something like:
var request = new Request {Number=2};
client.PostAsync("url", request)
I found a similar implementation, but that does not seems to be .netcore compatible:
https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/5.2.4-preview1
Is there anything similar for .netcore?
Thanks
You will still need to serialize the object to a JSON string.
The referenced Microsoft.AspNet.WebApi.Client library in question would have the PostAsJsonAsync extension method along with many others for extending HttpClient.
Which internally may have looked like this.
public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string requestUri, T obj) {
var json = JsonConvert.SerializeObject(obj);
var content = new StringContent(json, Encoding.UTF8, "application/json");
return client.PostAsync(requestUri, content);
}
and used like
using System.Net.Http;
//...
var request = new Request { Number = 2 };
var response = await client.PostAsJsonAsync("url", request);

Razor Pages and Json

I am developing an application that consults a Web API from an affiliate website, gets data in json format and I want to simply present this data in a page.
public async Task<IActionResult> OnPostAsync(string urljson)
{
var httpClient = new HttpClient();
var resultado = await httpClient.GetStringAsync(urljson);
Produto.Rootobject Produtos = JsonConvert.DeserializeObject<Produto.Rootobject>(resultado);
return RedirectToPage("ListaSugestoes", Produtos);
}
The code I added in the page I want the results to appear is:
using Buyit.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Buyit.Pages
{
public class ListaSugestoesModel : PageModel
{
private readonly Produto.Rootobject _jsonProdutos;
public ListaSugestoesModel(Produto.Rootobject jsonProdutos)
{
_jsonProdutos = jsonProdutos;
}
public JsonResult OnGetProdutos()
{
return new JsonResult(_jsonProdutos);
}
}
}
Is it done right? I had it work using a Controller, but I am trying to learn Razor Pages and want to know if that's possible to implement using it. Tks!

How to respond via an JsonResult from Asp.Net Core middleware?

I would like to respond via a JsonResult from a piece of Asp.Net Core middleware but it's not obvious how to accomplish that. I have googled around alot but with little success. I can respond via a JsonResult from a global IActionFilter by setting the ActionExecutedContext.Result to the JsonResult and that's cool. But in this case I want to effectively return a JsonResult from my middleware. How can that be accomplished?
I framed the question with regard to the JsonResult IActionResult but ideally the solution would work for using any IActionResult to write the response from the middleware.
Middleware is a really low-level component of ASP.NET Core. Writing out JSON (efficiently) is implemented in the MVC repository. Specifically, in the JSON formatters component.
It basically boils down to writing JSON on the response stream. In its simplest form, it can be implemented in middleware like this:
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
// ...
public async Task Invoke(HttpContext context)
{
var result = new SomeResultObject();
var json = JsonConvert.SerializeObject(result);
await context.Response.WriteAsync(json);
}
For others that may be interested in how to return the output of a JsonResult from middleware, this is what I came up with:
public async Task Invoke(HttpContext context, IHostingEnvironment env) {
JsonResult result = new JsonResult(new { msg = "Some example message." });
RouteData routeData = context.GetRouteData();
ActionDescriptor actionDescriptor = new ActionDescriptor();
ActionContext actionContext = new ActionContext(context, routeData, actionDescriptor);
await result.ExecuteResultAsync(actionContext);
}
This approach allows a piece of middleware to return output from a JsonResult and the approach is close to being able to enable middleware to return the output from any IActionResult. To handle that more generic case the code for creating the ActionDescriptor would need improved. But taking it to this point was sufficient for my needs of returning the output of a JsonResult.
As explained by #Henk Mollema, I have also made use of Newtonsoft.Json JsonConvert class to serialize the object into JSON through SerializeObject method. For ASP.NET Core 3.1 I have used JsonConvert inside the Run method. Following solution worked for me:
Startup.cs
using Newtonsoft.Json;
// ...
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Run(async context =>
{
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(new
{
message = "Yay! I am a middleware"
}));
});
}
}
As of ASP.NET Core 5.0, you can use WriteAsJsonAsync to write JSON to the response stream. This method handles serialization and setting the content type header appropriately.
For example
using Microsoft.AspNetCore.Http;
// ..
public async Task InvokeAsync(HttpContext context)
{
var result = new SomeResultObject();
await context.Response.WriteAsJsonAsync(result);
}

How to run JUnit testing on Firebase Java with authentication?

I am currently using Firebase Authentication in my mobile app. The back end is a Spring boot application. The REST APIs on the back end relies on a token generated from Firebase Authentication to retrieve the Firebase UID (verifyIDToken method) of a user to perform further functions.
Currently, I notice that in Firebase Java API (server-based), there is no way of generating a token for a user, thus there is no easy way for me to do JUnit testing on the server that relies on user authentication. Anyone has clues on how to do so?
This is the sample code that does not work:
#RequestMapping(value = "/api/subscribeChannel/{channelid}", method = RequestMethod.GET, produces = "application/json")
public DeferredResult<Object> subscribeChannel(#PathVariable Long channelid,#RequestHeader(value=FIREBASETOKEN, required = true) String idToken) {
DeferredResult<Object> result = new DeferredResult<Object>(DEFERREDTIMEOUT);
// test it out with a locally generated token
idToken = FirebaseAuth.getInstance().createCustomToken("valid Uid");
Task<FirebaseToken> task = FirebaseAuth.getInstance().verifyIdToken(idToken)
.addOnSuccessListener(new OnSuccessListener<FirebaseToken>() {
#Override
public void onSuccess(FirebaseToken decodedToken) {
String uid = decodedToken.getUid();
logger.info("Subscribe channel on success");
// do something
ret.setStatus("success");
ret.setMessage("channel id " + channelid + " subscribed");
result.setResult(ret);
} else {
result.setErrorResult(retStatus.getMessage());
}
}
}) .addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception arg0) {
Exception te = new TokenNotFoundException(idToken);
logger.error("Token Not Found for " + idToken);
result.setErrorResult(te);
}
});
return result;
}
The custom token you get is different from the ID token that you use to log on. To get an id token from a custom token, do this:
private static final String ID_TOOLKIT_URL =
"https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken";
private static final JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
private static final HttpTransport transport = Utils.getDefaultTransport();
private static final String FIREBASE_API_KEY = "<your api key here>";
private String signInWithCustomToken(String customToken) throws IOException {
GenericUrl url = new GenericUrl(ID_TOOLKIT_URL + "?key="
+ FIREBASE_API_KEY);
Map<String, Object> content = ImmutableMap.<String, Object>of(
"token", customToken, "returnSecureToken", true);
HttpRequest request = transport.createRequestFactory().buildPostRequest(url,
new JsonHttpContent(jsonFactory, content));
request.setParser(new JsonObjectParser(jsonFactory));
com.google.api.client.http.HttpResponse response = request.execute();
try {
GenericJson json = response.parseAs(GenericJson.class);
return json.get("idToken").toString();
} finally {
response.disconnect();
}
}
The Java API to generate custom tokens is documented under Create custom tokens using the Firebase SDK.
From there:
String uid = "some-uid";
String customToken = FirebaseAuth.getInstance().createCustomToken(uid);