Submit form to another page with a PUT Http request C# - c#

I'm fairly new to C# and I'm trying to accomplish the following:
The end user has a switch button on a page where he can activate a service.This switch submits a form with data, that is sent asyncronous to another page where this same page needs to do a PUT request to activate the service.
Depending on what is returned, it will show a sucess or an error message in the same page where the user can activate the service.
There are two things new to me with Http requests in C#:
How do I make the request on the page load, as in, the form is submitted to this page and it will make the request right away.
How to retrieve the response back to the activation page?
So far this is my C# code on the page that needs to make the request.(The form is already submitting to this page):
public class FormValues
{
public string Id { get; set; }
public string SubId { get; set; }
}
private static async Task<string> ServiceActivation()
{
var user = User.GetUser();
var valuesFromForm = new FormValues
{
Id = Dynamicweb.Context.Current.Request.Form["id"],
SubId = Dynamicweb.Context.Current.Request.Form["subId"]
};
string requestUri = $"https://somedomain/api/{valuesFromForm.Id}/activate-service/{valuesFromForm.SubId}";
var httpClient = new HttpClient();
string _ContentType = "application/json";
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(_ContentType));
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {user.Token()}");
var json = JsonConvert.SerializeObject(valuesFromForm);
var httpContent = new StringContent(json);
var response = await httpClient.PutAsync(requestUri, httpContent);
response.EnsureSuccessStatusCode();
var content = response.Content.ReadAsStringAsync().Result;
return content;
}
In the Razor view:
#{
#ServiceActivation()
}

Related

How can I execute an url call from C# code on a ASP website on a ASCX page?

I need to call a Custom protocol (something like: "custom:signDocs?param1=value?param2=value") that is registered on a client.
I have a working one that is executed via JavaScript on a button click.
But I need to call the url to execute the program I have on the clients pc.
The program is for signing documents and sending them back to the server, and, in the code I have a 15min timer that waits for the status of the documents to change to signed then it shows the documents to the user.
I also tried using webrequest:
//Method that uses the webrequest
{
System.Net.WebRequest.RegisterPrefix("customProtocolName", new PrototipoIDPTRequestCreator());
System.Net.WebRequest req = System.Net.WebRequest.Create(protocolUrlWithParams);
var aux = req.GetResponse();
}
internal class CustomRequestCreator : System.Net.IWebRequestCreate
{
public WebRequest Create(Uri uri)
{
return new CustomWebRequest(uri);
}
}
class CustomWebRequest: WebRequest
{
public override Uri RequestUri { get; }
public CustomWebRequest(Uri uri)
{
RequestUri = uri;
}
}
But this does nothing, I do not know it its even the right path...
Does anyone know of a way to accomplish this?
You can use HttpClient from System.Net.Http like the following example.
Simple get call from a test api endpoint.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("YOUR_BASE_URL"); //https://localhost:8000
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/test"); //api uri
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
}
Note: For more details refer, HttpClient Doc

Is it possible to access a webpage that uses sessions on a xamarin forms app?

I have a web page(.../ui/mydashboard.aspx ) which I want to display on my xamarin forms app, the problem is the web page doesn't use query parameters to provide for the users authentication details is it possible to access the web page(.../ui/mydashboard.aspx ) without having to go through the login page in my mobile app?
public Dashboard ()
{
InitializeComponent ();
webView.Source = "http://dev.webapp.com/ui/mydashboard.aspx";
}
You can send the data as the body of post request .If you don't want to let user input it , you can set a default value .
HttpClient client = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) };
// set the params here
HttpContent content = new StringContent(JsonConvert.SerializeObject(objectToPost), Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await client.PostAsync(new Uri("http://your.url"), content);
if (response.IsSuccessStatusCode) {
var responseFromServer = await response.Content.ReadAsStringAsync();
}
else {
// handle errors
}

Spotify authorization login call in wrong url

I am working on a simple web app to display my currently playing song. I have set up a Spotify account an received a clientId and client secret.
I try to request the initial token, for further communication with the spotify api.
I am displaying the received login html, i try to log in, but nothing happens, it just says "There went something wrong ..." above the login form. At this point i checked the spotify dashboard and whitlisted all the local callback urls, but i am still getting this message an nothing is happening.
I checked the browser dev tools and saw something odd (at least i belive its odd).
The login call redirects to "https://losthost:5001/api/login" which leads to a 404.
public async Task<IActionResult> Connect()
{
var client = new HttpClient();
var clientId = "clientId";
var redirectUrl = HttpUtility.UrlEncode("http://localhost:5000/Spotify/Callback/");
var url = $"client_Id={clientId}&response_type=code&redirect_uri={redirectUrl}";
var result = await client.GetAsync($"https://accounts.spotify.com/authorize?{url}");
if (result.Content.Headers.ContentType.MediaType == "text/html"){
var spotifyLoginHtml = await result.Content.ReadAsStringAsync();
return new ContentResult()
{
Content = spotifyLoginHtml,
ContentType = "text/html",
};
}
else
{
//var accessToken = await result.Content.ReadAsStringAsync();
//return RedirectToAction("DevicesSelection");
}
return View();
}
I think my problem is the wrong login call from the spotify login html, but i dont know why this happens or how to fix it.
Edit:
Added image with initial error (Uncaught in promise) and wrong api/login call
The redirect_uri :
The URI to redirect to after the user grants or denies permission. This URI needs to have been entered in the Redirect URI whitelist that you specified when you registered your application. The value of redirect_uri here must exactly match one of the values you entered when you registered your application, including upper or lowercase, terminating slashes, and such.
Spotify provides article available that covers the authentication and authorization setup and flow step-by-step.
So that if http://localhost:5000/Spotify/Callback/ is your redirect url , you should firstly add the url to Redirect URI whitelist in dashboard :
And in your application you should have route matches http://localhost:5000/Spotify/Callback/ to get the code via query string , and then use code to acquire access token for accessing Spotify APIs . Here is a code sample :
class SpotifyAuthentication
{
public string clientID = "xxxxxxxxxxxxxxxxxxxxx";
public string clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
public string redirectURL = "https://localhost:44363/callback";
}
public class HomeController : Controller
{
SpotifyAuthentication sAuth = new SpotifyAuthentication();
[HttpGet]
public ContentResult Get()
{
var qb = new QueryBuilder();
qb.Add("response_type", "code");
qb.Add("client_id", sAuth.clientID);
qb.Add("scope", "user-read-private user-read-email");
qb.Add("redirect_uri", sAuth.redirectURL);
return new ContentResult
{
ContentType = "text/html",
Content = #"
<!DOCTYPE html>
<html>
<head>
<meta charset=""utf-8"">
<title>Spotify Auth Example</title>
</head>
<body>
<button>Authenticate at Spotify</button>
</body>
</html>
"
};
}
[Route("/callback")]
public ContentResult Get(string code)
{
string responseString = "";
if (code.Length > 0)
{
using (HttpClient client = new HttpClient())
{
Console.WriteLine(Environment.NewLine + "Your basic bearer: " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(sAuth.clientID + ":" + sAuth.clientSecret)));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(sAuth.clientID + ":" + sAuth.clientSecret)));
FormUrlEncodedContent formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("redirect_uri", sAuth.redirectURL),
new KeyValuePair<string, string>("grant_type", "authorization_code"),
});
var response = client.PostAsync("https://accounts.spotify.com/api/token", formContent).Result;
var responseContent = response.Content;
responseString = responseContent.ReadAsStringAsync().Result;
}
}
return new ContentResult
{
ContentType = "application/json",
Content = responseString
};
}
}
Code reference : https://github.com/bmsimons/dotnet-core-spotify-authentication and blog .
And of course you can use Spotify middleware , here is a code sample .

How to add a custom header to HttpClient()?

I'm trying to add a custom header to the request header of my web application. In my web application im retrieving data from a web api, in this request i want to add a custom header which contains the string sessionID. I'm looking for a general solution so that I dont have to add the same code before every call I make.
My Controller looks like this:
[HttpGet]
public async Task<ActionResult> getCall()
{
string url = "http://localhost:51080/";
string customerApi = "customer/1";
using (var client = new HttpClient())
{
//get logged in userID
HttpContext context = System.Web.HttpContext.Current;
string sessionID = context.Session["userID"].ToString();
//Create request and add headers
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Custom header
//Response
HttpResponseMessage response = await client.GetAsync(customerApi);
if (response.IsSuccessStatusCode)
{
string jsondata = await response.Content.ReadAsStringAsync();
return Content(jsondata, "application/json");
}
return Json(1, JsonRequestBehavior.AllowGet);
}
}
Hope anybody can help!
Thanks in advance!
Try this:
client.DefaultRequestHeaders.Add("X-Version","1");
Collection behind DefaultRequestHeaders has Add method which allows you to add whatever header you need:
client.DefaultRequestHeaders.Add("headerName", sesssionID);

C# JSON POST connect (Method not allowed)

I have problem with connect to JSON server.
In user-manual:
The Interface is implemented as a standard HTTP Service. Using the service requires an authentication through the “Login” method. A Session Id is returned on success which has to be passed on every function call unless otherwise stated.
The expected data format when sending or receiving data is JSON.
All data must be passed using POST.
The session Id is of type Guid
Example:
Login
Description: Used to authenticate a user.
Url: /Login
Signature: Guid Login(string id, string username, string password)
END OF MANUAL
I wrote this code:
var webAddr = "https://xxx/Login";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"Login\":[{"
+ "\"id\" : 1213213,"
+ "\"username\" : asdasdasd,"
+ "\"password\" : \"adasdsadasd\","
+ "}]}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
MessageBox.Show(result.ToString());
}
And message is: Method not allowed.
How can I send and recive data from this serwer?
You are formatting your JSON incorrectly. The JSON should look like this:
{"id":"1213213","username":"asdasdasd","password":"adasdsadasd"}
Notice: quotes around each name and value. And "Login" should not be part of the JSON.
However, the problem is really that you are doing this all manually. Instead, let .NET format the JSON for you and handle the HTTP request. To do this, create a structure for the arguments:
class Login
{
public string id { get; set; }
public string username { get; set; }
public string password { get; set; }
}
Use NuGet to add references to "Json.Net" and "Microsoft ASP.NET Web API Client Libraries." Now you can write this:
static async Task Login()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://www.censored.de/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.Timeout = TimeSpan.FromSeconds(30);
Login l = new Login() { id = "12345", password = "abcde", username = "safsdfasdf" };
var sTemp = JsonConvert.SerializeObject(l); // DEBUG: Just so I can see the JSON
var response = await client.PostAsJsonAsync("/censored/Service.svc/Login", l);
Guid g;
if (response.IsSuccessStatusCode)
{
g = await response.Content.ReadAsAsync<Guid>(); // This gives you the GUID
}
//DEBUG:
// var rawResponse = await response.Content.ReadAsStringAsync();
// Console.WriteLine(response);
}
}
Notice that I used "async" and "await" keywords. If you are not familiar with calling an async function, you can change the "await" line to this temporarily:
var response = await client.PostAsJsonAsync("/censored/Service.svc/Login", l).Result;
This results in a 400 Bad Request with this message.
{"ErrorMessage":"Die Anmeldedaten sind ungültig.","StackTrace":null}
Which Google tells me means that the credentials are wrong. I assume that is the response one would expect with this user/password combination.

Categories

Resources