Rest API Working examples in C#

  • 26 November 2019
  • 4 replies
  • 526 views

Does anyone actually have any working examples of using the Rest API to connect and extract the JSessionID ?
Seems that documentation is very hard to find in this area

4 replies

Here a simple example using RestSharp Client


using System;
using System.Linq;
using RestSharp;

namespace SomeNamespace
{
class Program
{
public class Login
{
public string user_name { get; set; }
public string account_id { get; set; }
public string password { get; set; }

public Login(string user, string account, string password)
{
this.user_name = user;
this.account_id = account;
this.password = password;
}
}

static void Main(string[] args)
{

string someUser = "someUser";
string someAccount = "someAccount";
string somePass = "somePassword";
var objLogin = new Login(someUser, someAccount, somePass);

//Create RestSharp Client
var client = new RestClient("https://yourRestEndpoint");

//Send login request
var loginRequest = new RestRequest("login", Method.POST);
loginRequest.AddJsonBody(objLogin);
var responseLogin = client.Execute(loginRequest);

//Pick-Up login Cookie and setting it to Client Cookie Container
client.CookieContainer = new System.Net.CookieContainer();
var authCookie = responseLogin.Cookies.First(a => a.Name == "JSESSIONID");
client.CookieContainer.Add(new System.Net.Cookie(authCookie.Name, authCookie.Value, authCookie.Path, authCookie.Domain));

//Send new request
int idUser = 1;
var getUserRequest = new RestRequest($"users/{idUser}", Method.GET);
var responseGetUser = client.Execute(getUserRequest);

Console.Read();
}
}
}
Thanks for posting this! It really gave me a jumpstart.
Badge

DO you have any example to login with axios and JavaScript 

hey @eluiz 

it really depends on how your code is written. This is only the Axios part.

Check this out:

const axios = require('axios');

// Function to perform login using Axios
async function login(username, password) {
try {
const apiUrl = 'http://localhost:8080/api/v1/login';
const requestBody = { username, password };

const response = await axios.post(apiUrl, requestBody);

// Assuming the API returns a token upon successful login
const authToken = response.data.token;
console.log('Login successful! Auth token:', authToken);
// You can store the token in a cookie or local storage for subsequent API requests.

return authToken;
} catch (error) {
console.error('Login failed:', error.message);
// Handle login failure appropriately (e.g., display an error message).
return null;
}
}

// Usage example:
const username = 'your_username';
const password = 'your_password';
login(username, password);

 

Reply