I have a WS that I call like this:
HttpResponseMessage response = await client.PostAsync(url, new StringContent(json));
the WS will throw an Exception (Forbidden) and in my Blazor application that made the PostAsync call, I will get an HttpResponseMessage with response code 405, not sure why its 405, it should be 403 (Postman returns 403).
I have enabled CORS (ServiceStack code):
Plugins.Add(new CorsFeature(allowedOrigins: "*",
allowedMethods: "GET, POST, PUT, DELETE, OPTIONS",
allowedHeaders: "*",
allowCredentials: true));
This is some Console.Writeline I did, just before the PostAsync:
Failed to load resource: the server responded with a status of 405 ()
** UPDATED **
This are the two methods:
public async Task<TResponse> PostAsync<TResponse, TRequest>(string requestUri, TRequest request)
{
string url = GetUrl(requestUri);
Console.WriteLine("URI: " + url);
string json = JsonConvert.SerializeObject(request);
Console.WriteLine($"{url} | {json}");
HttpResponseMessage response = await client.PostAsync(url, new StringContent(json));
return await GetResponseOrThrowHttpException<TResponse>(response);
}
private async Task<T> GetResponseOrThrowHttpException<T>(HttpResponseMessage response)
{
Console.WriteLine($"GetResponseOrThrowHttpException: {response.StatusCode}");
string responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine($"GetResponseOrThrowHttpException ContentStringResult: |{responseString}|");
if (!response.IsSuccessStatusCode)
{
Newtonsoft.Json.Linq.JObject jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseString);
string responseStatusString = jsonObject["ResponseStatus"].ToString();
Console.WriteLine($"GetResponseOrThrowHttpException 4: {responseStatusString}");
ResponseStatus responseStatus = JsonConvert.DeserializeObject<ResponseStatus>(responseStatusString);
Console.WriteLine($"Throwing HttpException: {response.StatusCode} {responseStatus.Message}");
throw new HttpException(response.StatusCode, responseStatus.Message);
}
return JsonConvert.DeserializeObject<T>(responseString);
}
When I try to get the string value of the response, it is empty:
string responseString = await response.Content.ReadAsStringAsync();
and the responseString is an empty (length 0) string.
If I run the exact same request in Postman, I get a valid response:
So, the response JSON, seen at the bottom in the image above, is what I want to work with in the Blazor app, and parse it as a JSON object and move on from there.
I also note that I get here a 403 error, which I expected, and in the Blazor app, I get a 405.
Is this a CORS issue even though I have enabled CORS on the WS side?
I guess your content should be posted like that:
new StringContent(json, Encoding.UTF8, "application/json")
Even if this is not the cause of your suffering, it's better to use this so...
Hope this helps...
Verify that you have setup proper CORS configuration for the domain.
Looks like you made call to another domain:port combination from your Blazor application. Even if this C#, all security rules inside browser still applies.
Related
This is a http request to the https://auth.monday.com/oauth2/authorize endpoint on asp.net 6. It should get the code parameter from that endpoint but it's returning a 500 response with html for some reason. This is part of my code grant flow because the API has oauth2.0.
public async Task<string> GetCode(string clientId, string redirect_uri)
{
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"https://auth.monday.com/oauth2/authorize{clientId}");
string json =
JsonSerializer.Serialize(
new
{
query = "code"
}
);
request.Content = new StringContent(json,
Encoding.UTF8, "application/json");
var response = await client.SendAsync(request);
var responseText = await response.Content.ReadAsStringAsync();
return responseText;
}
Are you missing a / in your endpoint by any chance? Should it not be https://auth.monday.com/oauth2/authorize/{clientId}?
HTTP 500 is an internal server error, this means that the server was unable to handle your request properly. If you have access to the server then I would look there as to why it was unable to handle your request. I don't see anything wrong in your request.
Having issues with my code [ Throwing an Unhandled exception: System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (Bad Request) ] when trying to connect to WebApi
This is my first time working with await/async methods, but I am needing to return
string msgTask = await response.Content.ReadAsStringAsync(); return msgTask;
At first my Console.WriteLine(await response.Content.ReadAsStringAsync(); returned:
BadRequest {"error":"Password must be at least 8 characters, with at least 1 of each alpha, number and special characters"}
But then I inserted this check: response.EnsureSuccessStatusCode(); which Throws the System.Net.Http.HttpRequestException
Full [top-level styled] Code Below (I am only using Console.WriteLine() to help with debugging, final code will only have return msgTask;) :
HttpRequest.GetHttpResponse();
await WattTime.PostRequest.RegisterUser();
public class HttpRequest
{
public static HttpClient client = new();
public static void GetHttpResponse()
{
// GetRequestMethod to use later
}
}
namespace WattTime
{
class PostRequest : HttpRequest
{
public static async Task<string> RegisterUser()
{
string Url = "https://api2.watttime.org/v2/register";
Dictionary<string, string> parameters = new()
{
{"username", "TestUser" },
{"password", "Password#1" },
{"email", "testuser#yahoo.com" },
{"org", "XYZ" },
};
var jsonDictionary = JsonConvert.SerializeObject(parameters);
var content = new StringContent(jsonDictionary, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(Url, content);
response.EnsureSuccessStatusCode();
string msgTask = await response.Content.ReadAsStringAsync();
Console.WriteLine(msgTask);
return msgTask;
}
}
}
UPDATE I changed the format of data being sent to the API var data = #"{ ""username"": ""TestUser900"", ""password"": ""Summer$21"", ""email"": ""test65349#yahoo.com""}";
and added var postData = JsonConvert.SerializeObject(data); var postData2 = JsonConvert.DeserializeObject(postData);
If I use Console.WriteLine(await response.Content.ReadAsStringAsync()) I receive the Status and User Created, but if I use return response.StatusCode.ToString(); nothing returns
Looks like you need to change your test data. I tried to run your data in Online API testing tool and it returned the same error and later when I changed the json data it returned status 200 OK. Also I observed that every time you need to send unique data or its returning error.
Your issue may be the # symbol in your data. If sent in the URL it will need to be URL encoded. See this list of characters that need encoding https://www.w3schools.com/tags/ref_urlencode.asp
You can use HttpUtility.UrlEncode to do this on your jsonDictionary variable, HttpServerUtility and WebUtility classes also have this static method.
Change this response.EnsureSuccessStatusCode(); to this
if(response.IsSuccessStatusCode){
//Code here
}
The code below works for sending a HTTP post to Webhook.site, but when doing the same request to my own azurewebsite the debugger stops at postasync and the ’response’ variable remains null.
My azure website returns 200 from json-string POST from ReqBin. My excel application can send working http posts to Webhook.site using the code below, just not to my own azurewebsite. What am I missing?
Some resources suggest SSL validation might cause problems? Not sure if this is the case.
private static readonly HttpClient client = new HttpClient();
public async Task<HttpResponseMessage> PostRequest(IRibbonControl control)
{
var content = new StringContent(json_object.ToString(), System.Text.Encoding.UTF8, "application/json");
//This is where i input my own website and it doesn't work
HttpResponseMessage response = await client.PostAsync("https://webhook.site/9b994ad0-81a1-496f-b910-d48d0567b1b8", content).ConfigureAwait(false);
var responseString = await response.Content.ReadAsStringAsync();
return response;
}
Thank you for your help.
To see result of postAsync method in debug execute 2 steps. Screenshot: postAsync debug
return HttpResponseMessage from method with postAsync:
private static async Task<HttpResponseMessage> methodWithPostAsync(){
...
response = await client.PostAsync(url, data);
return response
}
call method and wait for response message status:
Task<HttpResponseMessage> content= methodWithPostAsync();
while (!content.IsCompleted)
{
Console.WriteLine("busy");
System.Threading.Thread.Sleep(1000);
}
I have create gandi api code for create domain and for that i have write below code, but it show me 400 bad request error
public async System.Threading.Tasks.Task<JsonResult> InsertDomain(DomainDetails domainDetails)
{
HttpResponseMessage response = new HttpResponseMessage();
try
{
var url = "https://api.gandi.net/v5/domain/domains";
using ( var client = new HttpClient() )
{
var json = new JavaScriptSerializer().Serialize(domainDetails);
HttpContent HttpContent = new StringContent(json, Encoding.UTF8, "application/json");
var MyHttpClient = new HttpClient();
MyHttpClient.DefaultRequestHeaders.Add("authorization", GANDI_API_Key);
response = await MyHttpClient.PostAsync(url, HttpContent);
}
}
catch ( Exception ex )
{
throw;
}
return Json(new { result = response }, JsonRequestBehavior.AllowGet);
}
but when i try to pass same data using postman then it's working fine below code is my postman data
Body
{
"fqdn":"dedasdom1906.com",
"owner":
{
"city":"Paris",
"given":"Alice",
"family":"Doe",
"zip":"75001",
"country":"FR",
"streetaddr":"5 rue neuve",
"phone":"+33.123456789",
"state":"FR-J",
"type":"0",
"email":"alice#example.org"
}
}
Header
authorization : Apikey
Content-Type : application/json
I havent worked with this endpoint, but you are missing the return type.
the next thing i would try is to paste json string directly in the StringContent.
please paste the correct string content(rename the variable)
if none of this help you, please give more details.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
For the https://api.gandi.net/v5/domain/domains endpoint, use HTTP GET (HttpClient.GetAsync) to retrieve a list of your domains. Use HTTP POST (HttpClient.PostAsync) to create a new domain.
If you're trying to POST JSON, I would use the PostAsJsonAsync method, example here:
static async Task<Uri> CreateProductAsync(Product product)
{
HttpResponseMessage response = await client.PostAsJsonAsync(
"api/products", product);
...
Also note your auth header needs to start with "apikey" though it looks like you have that working. Curl example:
curl -X GET \
https://api.gandi.net/v5/domain/domains \
-H 'authorization: Apikey your-api-key'
https://api.gandi.net/docs/domains/
I'm trying to consume data in my front-end which calls a API Broker and this API Broker calls my API. In my front-end I'm getting JSON data returned JSON with alot of backslashes in it. How can i prevent this? see code and errors below:
Consuming my API in my front-end:
[HttpGet]
public async Task<ActionResult> getCall()
{
string url = "http://localhost:54857/";
string operation = "getClients";
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
client.DefaultRequestHeaders.Add("loggedInUser", sessionID);
//Response
HttpResponseMessage response = await client.GetAsync(operation);
if (response.IsSuccessStatusCode)
{
string jsondata = await response.Content.ReadAsStringAsync();
return Content(jsondata, "application/json");
}
return Json(1, JsonRequestBehavior.AllowGet);
}
}
My Api Broker gets the request and executes this:
As you can see the response content contains alot of backslashes.
This response is going back to my front-end where i receive the following content:
In this response there are even more backslashes added.
I hope someone recognizes this problem and knows a solution.
Thanks in advance!
I fixed it by serializing the string to a JSON object and than deserialize it .