The question is following:
I am having very simple POST method on the server side:
[HttpPost]
[Route("//api/loggeduser")]
public void Post([FromBody] LoggedUser loggedUser)
I am trying to call it from the client side:
var loggedUser = new LoggedUser
{
UserName = userName,
Logged = true
};
var json = JsonConvert.SerializeObject(loggedUser);
HttpClient _httpClient = new HttpClient();
HttpContent httpContent = new StringContent(json);
response = await _httpClient.PostAsync("https://localhost:44311/api/loggeduser", httpContent);
And I always getting error 400. What I am doing wrong? Any suggestions? Thanks in advance.
I think it might work if you tell the StringContent which encoding and content type it should use, like this:
HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");
You have an invalid syntax. Whatever information you're attempting to send it is not formatted in a way that the server is willing to accept. You need to check the parameters and make sure you have it written in the correct syntax.
You can try to let content-type to be application/json.
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
Related
I am working on this helper method that will call an API using the body section. I am passing in the url and data in the model. Then I SerializeObject the model, but I am not sure what to return I get the error message about the response.Content is not found.
public static async System.Threading.Tasks.Task<HttpResponse> HttpClientHandlerAsync(string url, object model)
{
var fullUrl = apiUrl + url;
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
Client.DefaultRequestHeaders.Add("Accept", "*/*");
Client.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer", "token");
var response = await Client.PostAsync(fullUrl, data);
return response;
}
Add await in front of your
await Client.PostAsync(fullUrl, data);
Because you're trying to get content of Task
I am not sure what to return I get the error message about the response.Content is not found.
Set a breakpoint and hover over the response to see the status code. You could have a 500 server error, authentication error etc.
Furthermore
using (var client = new HttpClient())
Do not do this. It doesn't work the way you think it does, it will starve your connection pool and eventually throw an exception. You need to define the HttpClient somewhere and continue to reuse the same instance.
Further reading if you care https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
I'm a trying to post the following request but I am getting a "Unsupported Media Type" response. I am setting the Content-Type to application/json. Any help would be appreciated. And as per comment below, if i change content as 'new StringContent(JsonConvert.SerializeObject(root), Encoding.UTF8, "application/json")' then i get bad request response
string URL = "https://test.com/api/v2/orders/"; //please note it is dummy api endpoint
var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(URL),
Headers = {
{ HttpRequestHeader.Authorization.ToString(), "Bearer ABcdwenlfbl8HY0aGO9Z2NacFj1234" }, //please note it is dummy bearer token
{ HttpRequestHeader.Accept.ToString(), "application/json;indent=2" },
{ HttpRequestHeader.ContentType.ToString(), "application/json" }
},
//Content =new StringContent(JsonConvert.SerializeObject(root), Encoding.UTF8, "application/json")
Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(root))
};
var response = client.SendAsync(httpRequestMessage).Result;
With HttpClient, some headers are counted as request headers, and others are counted as content headers. I'm not sure why they made this distinction really, but the bottom line is that you have to add headers in the correct place.
In the case of Content-Type, this can be added as part of the StringContent constructor, or to the constructed StringContent object.
My approach is to use the constructor:
Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(root), System.Text.Encoding.UTF8, "application/json");
Or alternatively set it afterwards:
Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(root))
Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
Note: If your issue still presents after making this change, then it's likely a server-side problem and you'll need to contact the maintainer of the API to ask what you're doing wrong.
I prefer using some third party wrappers like FluentClient
Note that you should not instance a new object for every request, O only did it for the sake of an example.
var client = new FluentClient("https://test.com/api/v2/orders/")
.PostAsync(URI)
.WithBody(root)
.WithBearerAuthentication("ABcdwenlfbl8HY0aGO9Z2NacFj1234");
var response = await client.AsResponse();
I want to send an HTTP GET with a request body. I know there is much heated debate about whether this should ever be done or not but I am not interested in debating it I simply want to do it. I'm using C# and ASP.NET and my code is below. Unfortunately it throws an exception "Cannot send a content-body with this verb type". Please, any help on how to get this done will be very appreciated!
// Serialize our concrete class into a JSON String
var stringPayload = JsonConvert.SerializeObject(memRequest);
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = u,
Content = httpContent
};
var result = httpClient.SendAsync(request).Result;
result.EnsureSuccessStatusCode();
var responseBody = result.Content.ReadAsStringAsync().ConfigureAwait(false);
public async static Task<RootUserData> getUSerLoggedIn(string userName, string password)
{
RootUserData rootUserData = new RootUserData();
var url = URlConstants.LOGIN_URL;
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{userName}:{password}");
httpClient.DefaultRequestHeaders.Add("content-type", "application/json");
httpClient.DefaultRequestHeaders.Add("cache-control", "no-cache");
} ;
}
I am using above code to make one Service call. I have to pass userEmailAddress in body as plain as shown in Postman Picture. Can You Please help me How to achieve this?
No... Its in Plain Text
Set your content mime type to "text/plain":
httpClient.DefaultRequestHeaders.Add("content-type", "text/plain");
And post a string:
var response = await httpClient.PostAsync(url, new StringContent(userName));
Content-Type should not be added like that, It didn't work in my case, and gave a wrong response, instead
Pass content-Type like this -
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
I'm trying to do something that seems like it should be simple: to send a JSON request to a PHP script on my webserver and get the response.
I can request the site without issue, I can read the response without issue, but for some reason this refuses to send the contents of my JSON data.
string url = "https://www.exampleserver.com/examplescript.php";
HttpClient client = new HttpClient(new Xamarin.Android.Net.AndroidClientHandler());
client.BaseAddress = new Uri(url);
string jsonData = #"{""key1"" : ""data1"",""key2"" : ""data2"",""key3"" : ""data3""}";
HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
string result = await response.Content.ReadAsStringAsync();
responsebox.Text = result;
Each time I run it the contents of responsebox.Text is replaced with the default contents of the page pointing out explicitly that there was no content in the $_POST data. (Even checked $_REQUEST to make sure it wasn't showing up as GET).
I know it's gotta be something simple, but I can't find it.