How to post and redirect with Razor Pages - asp.net-core

I do integration with payment gateway, which required post method. So I need to redirect from my page including post data to the payment gateway application under https
Following by this answer on this questions:
Post Redirect to URL with post data
How to make an HTTP POST web request
I not able found the right answer for my problem.
I'am using razor pages. Here is my code snippet
public async Task<IActionResult> OnGetAsync(int id)
{
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://example/payment/v1/easy", content);
var responseString = await response.Content.ReadAsStringAsync();
return Content(responseString);
}
I successfully get the response, but when I do return Content(responseString);. The page just show text only. Any idea how to solved this problem?

Related

Unauthenticated requests are not allowed. Take out a new plan or start a free trial at https://pro.bitcoinaverage.com

I want to print BTC conversion to other currencies. I am using bitcoinaverage. On the browser, the URL is not working. The screen displays this "Unauthenticated requests are not allowed. Take out a new plan or start a free trial at https://pro.bitcoinaverage.com". I am using Flutter. On console, it is giving a 404 error. The following is the code snippet.
const bitcoinAverageURL = 'https://apiv2.bitcoinaverage.com/indices/average/ticker';
Future getCoinData(String selectedCurrency) async {
var authKey = '$bitcoinAverageURL/BTCAUD';
http.Response response = await http.get(Uri.parse(authKey));
if (response.statusCode == 200) {
var decodedData = jsonDecode(response.body);
double current = decodedData['last'];
return current.toStringAsFixed(0);
} else {
print(response.statusCode);
throw 'Problem with get request';
}
From documentation:
All requests to our API must be authenticated with your public key.
You need to autrhorize on API site and get your API access token. API usage described in Official documentation.
Try to add your API key to header:
await http.get(
Uri.parse(url),
headers: {
'x-ba-key': 'your_api_key',
},
);

does the data sent to the server using http Post update the servers API url?

Im a newbie to flutter so please if you think the question context is wrong update it, im fetching a data from an SQl server to my flutter app, and i also want to send the users info back to the server after they fill out a form, im using the http.post and i get the response’s body correctly but when i open the Server Url (api url) i dont see it updated with the new info i posted to it, can someone please tell me how Post is supposed to work?
I'm new to Flutter too, this is a working example of how i understand it
class HttpService {
createUser(String name, String lastname) async {
Map data = {'name': name, 'lastname': lastname};
var body = json.encode(data);
var jsonResponse = null;
var response = await http.post(serverUrl + "/create/",
headers: {
HttpHeaders.authorizationHeader: '**Token_here_if_you_use_it**',
HttpHeaders.contentTypeHeader: "application/json",
}, body: body);
jsonResponse = json.decode(response.body);
if (response.statusCode == 201) {
jsonResponse = json.decode(response.body);
if (jsonResponse != null) {
print(jsonResponse.toString());
}
} else {
print(jsonResponse.toString());
}
}
}
In your main.dart :
final HttpService httpService = HttpService();
httpService.createUser(name,lastname);

How Do I get API Response Status Code Only with Blazor?

I need your help guys. I'm developing a front-end with Blazor which sends request to ASP.Net Core.
I have the following code which gets an API response, in this case it returns the entire body of the response. What I'm trying to get here is the status code of the response only, example (200).
await Http.SendJsonAsync(HttpMethod.Post, "https://da3.mock.pstmn.io/api/register", CurrentUser);
var response = await Http.GetStringAsync("/api/register");
Console.WriteLine(response);
Use the other GetAsync method.
//var response = await Http.GetStringAsync("/api/register");
//Console.WriteLine(response);
var response = await Http.GetAsync("/api/register");
Console.WriteLine(response.StatusCode); // also see response.IsSuccessStatusCode
For POST method you could use SendAsync, you need to use PMC to install Newtonsoft.Json package firstly:
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("POST"),
RequestUri = new Uri("https://localhost:5001/api/default"),
Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(CurrentUser))
};
requestMessage.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue(
"application/json");
var result = await Http.SendAsync(requestMessage);
var responseStatusCode = result.StatusCode;
For GET method,what Henk Holterman has suggested (use Http.GetAsync) works well.
Refer to
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-3.0#httpclient-and-httprequestmessage-with-fetch-api-request-options

Xamarin, redirect to page if status code is not Ok

I have REST API that returns if user exists or not by email.
If user exists and I am getting back status OK from API all works fine, but when API response with 404 my app crash. I can't figure out how to check if status is ok or not before app crash and redirect user to register page in case user is not found by API.
Here is code that makes request to api:
string getuserUrl = $"https://localhost:99282/api/users/{email}";
var client = new HttpClient();
var uri = new Uri(getuserUrl);
var result = await client.GetStringAsync(uri);
var userResult = JsonConvert.DeserializeObject<User>(result);
return userResult;
You can use below code to identify whether the API call is success or not.
String URL = "https://localhost:99282/api/users/{email}";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(URL);
try
{
HttpResponseMessage response = await client.GetAsync(URL);
if (response.IsSuccessStatusCode)
{
// Code 200 - If the API call is sucess
// You redirect to another page
}
else
{
// Show alert for failed calls
}
}
catch (Exception ex)
{
return null;
}
}

Web API Client Posting Not Hitting Database

Kindly help with ASP.NET MVC 4 Web Api project. I can retrieve JSON from my api controller without hitch, and posting seems to work (my UI is updated), but data is not hitting the database.
// POST api/todoes
public HttpResponseMessage Post(Todo item)
{
item = _db.Todoes.Add(item);
var response = Request.CreateResponse(HttpStatusCode.Created, item);
string uri = Url.Link("DefaultApi", new { id = item.TodoId });
response.Headers.Location = new Uri(uri);
return response;
}
self.create = function (formElement) {
// If valid, post the serialized form data to the web api
//$(formElement).validate();
//if ($(formElement).valid()) {
$.post(baseUri, $(formElement).serialize(), null, "json")
.done(function (o) { self.todoes.push(o); });
//}
}
'Am I doing something wrong?
Thanks all. I have the answer now ... _db.SaveChanges() commits to database.