Post string to Rest API results in 400 Bad Request - json

Sending a post request with a json object transformed into HttpContent, but the result is a 400 Bad request.
Sender
HttpClient _client = new HttpClient();
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var jsonObject = new JObject(new JProperty("id", Id), new JProperty("image", face));
var strJson = JsonConvert.SerializeObject(jsonObject);
var response = _client.PostAsync(_settings.Uri,
new StringContent(strJson, Encoding.UTF8, "application/json"));
Receiver
[HttpPost]
public IActionResult Post([FromBody]string value)
Could you please give me an advise on how to overcome 400 error?

You current code sends an object serialized to json while ASP.NET Core action expects a string serialized to json. The easiest solution would be repeated data serialization
var objectJson = JsonConvert.SerializeObject(jsonObject);
var stringJson = JsonConvert.SerializeObject(objectJson);
var response = _client.PostAsync(_settings.Uri, new StringContent(stringJson, Encoding.UTF8, "application/json"));

It appears that you have an extra Parentheses in your call
var response = _client.PostAsync(_settings.Uri, (new StringContent(strJson, Encoding.UTF8, "application/json"));
(new
Try removing that first.
Cheers

Related

Why 2 Different JSON Results with String Parameter Search using RestSharp?

If I hard code the band name in my client request with RestSharp I get the results I expect. If I pass in the String I get a different result set. I checked the url it formed and they are the same. Any ideas? I don't use both, I will comment one out and use the other for testing this scenario.
ArtistInfoResponse IMusicRepository.GetArtistResponse(string artistName)
{
var client = new RestClient($"https://api.deezer.com/search?q=artist:{artistName}");
// returns this as url https://localhost:44343/Home/ArtistInformation?artistName=Dave%20Matthews%20Band
var client = new RestClient($"https://api.deezer.com/search?q=artist:\"Dave Matthews Band\"");
// returns this in url https://localhost:44343/Home/ArtistInformation?artistName=Dave%20Matthews%20Band
var request = new RestRequest(Method.GET);
var cancellationTokenSource = new CancellationTokenSource();
IRestResponse response = client.Execute(request);
if (response.IsSuccessful)
{
// Deserialize the string content into JToken object
var content = JsonConvert.DeserializeObject<JToken>(response.Content);
// Deserialize the JToken object into our ArtistInfoResponse Class
return content.ToObject<ArtistInfoResponse>();
}
return null;
}

Http get request giving forbidden response in windows phone 8

HTTP "POST" data with login credentials to the BASEn server using API URL, in response it is giving a status 200, OK.
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("mode", "login"),
new KeyValuePair<string, string>("user", logintxtbx.Text),
new KeyValuePair<string, string>("password", passtxtbx.Text)
};
httpClient = new HttpClient(new HttpClientHandler());
HttpResponseMessage response = await httpClient.PostAsync("https://xx-yyy.com/auth", new FormUrlEncodedContent(values)); var strin = response.StatusCode.ToString();
var responseString = await response.Content.ReadAsStringAsync();
MessageBox.Show("login Success");
GetFullResponse(httpClient);
}
After validating my credentials, the server will create a session to me if i try to do "GET" HTTP by using another urls, it should gives my required data but this thing was not happening, every time iam getting "403" forbidden response.
This is the code using for "GET" data.
var uri = new Uri("https://xx-yyy.com/_ua/web/web/v1/xyz/?xyx=1431369000000&end=1431436740000&_=1431436741550");
var Response = await httpClient.GetAsync(uri);
var statusCode = Response.StatusCode;
Response.EnsureSuccessStatusCode()
var ResponseText = await Response.Content.ReadAsStringAsync();
i don't know whats wrong, i was doing.
Can any one suggest me how can i do this to be happen.
var handler = new HttpClientHandler();
var cookieContainer = handler.CookieContainer;
var client = new HttpClient(handler);
store cookies using cookieContainer and use them to authenticate the future calls using the same way as on web.
Store the cookies to the phone using IsolatedStorageSettings
Reference for more details here

Returning HttpResponseMessage from MVC HttpPost, with content of JSON

My first post on StackOverflow but I am a long time lurker! Hopefully I canget some help on an issue I'm working on.
I am trying to achieve the following. The code below is setting the content to be a JSON string which contains the following...
{
"access_token": "value1",
"expires_in": "value2",
"client_in": null,
"scope": "value3"
}
and here is the code which sends the HttpResponseMessage back to the client.
[HttpPost]
public HttpResponseMessage token(string grant_type,
string code,
string client_id,
string client_secret,
string redirect_uri)
{
WpOAuth2TokenRetValSuccessVM OA2_Success = new WpOAuth2TokenRetValSuccessVM();
OA2_Success.access_token = "value1";
OA2_Success.client_in = client_id;
OA2_Success.expires_in = "value2"; //...The number of seconds left in the lifetime of the token
OA2_Success.scope = "value3"; //...Each access token can have only 1 scope
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
string strJson = JsonConvert.SerializeObject(OA2_Success, Newtonsoft.Json.Formatting.Indented);
StringContent n = new StringContent(strJson, Encoding.UTF8, "application/json");
response.Content = n;
return response;
}
Now then, on the client side for the life of me I cannot get the JSON string back out of the content. Here is the code that I am using to read the content.
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>(str_KEY1, str_VALUE1));
postData.Add(new KeyValuePair<string, string>(str_KEY2, str_VALUE2));
postData.Add(new KeyValuePair<string, string>(str_KEY3, str_VALUE3));
postData.Add(new KeyValuePair<string, string>(str_KEY4, str_VALUE4));
postData.Add(new KeyValuePair<string, string>(str_KEY5, str_VALUE5));
HttpContent content = new FormUrlEncodedContent(postData);
httpClient.PostAsync(strURI, content).ContinueWith(requestTask =>
{
// Get HTTP response from completed task.
HttpResponseMessage response = requestTask.Result;
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously as string and write out
var responseValue = response.Content.ReadAsStringAsync();
responseValue.Wait();
string n = responseValue.Result;
var i = 0;
});
Now then, string n's content is as follows, but how do I get at the JSON???
Thanks all.
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
Content-Type: application/json; charset=utf-8
}
Sounds like you figured out the problem, but it should be noted that since you're using Web API, there's no need to serialize the data and build the HttpResponseMessage yourself; let the framework do it for you:
[HttpPost]
public WpOAuth2TokenRetValSuccessVM token(string grant_type,
string code,
string client_id,
string client_secret,
string redirect_uri)
{
return new WpOAuth2TokenRetValSuccessVM
{
access_token = "value1",
client_in = client_id,
expires_in = "value2",
scope = "value3"
};
}

How to send POST request with parameters asynchronously in windows phone 8

I would like to send POST request in windows phone 8 environment my code is running successfully but i am getting NotFound exception. Its mean is i want to POST some data but i am sending null. So please let me know how to send POST Request asynchronously with Data in windows phone 8 environmet. I tried following links but not helpful.
link link2
I approached like this
private async Task<LastRead> SyncLastReadPOST(LastRead lastreads, bool actionStatus)
{
string jsondata = "";
actionStatus = false;
apiData = new LastReadAPI()//It is global variable from apiData this object has the information
{
AccessToken = thisApp.currentUser.AccessToken,
Book = lastreads.Book,
Page = lastreads.Page,
Device = lastreads.Device
};
jsondata = Newtonsoft.Json.JsonConvert.SerializeObject(apiData);
LastRead responsedData = new LastRead();
Uri lastread_url = new Uri(string.Format("{0}lastread", url_rootPath));
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(lastread_url);
webRequest.ContentType = "application/json";
webRequest.Accept = "application/json;odata=verbose";
webRequest.Method = "POST";
webRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webRequest);
}
catch { }
return responsedData;
}
private void GetRequestStreamCallback(IAsyncResult ar)
{
HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
Stream postStream = request.EndGetRequestStream(ar);
var input = Newtonsoft.Json.JsonConvert.SerializeObject(jsondata);//jsondata is my global data variable in json format.
byte[] byteArray = Encoding.UTF8.GetBytes(input);
postStream.WriteAsync(byteArray, 0, byteArray.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseStreamCallback), request);
}
private void GetResponseStreamCallback(IAsyncResult ar)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)ar.AsyncState;
HttpWebResponse response;
//In following line i am getting the exception notFound.
response = (HttpWebResponse)webRequest.EndGetResponse(ar);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReaders = new StreamReader(streamResponse);
var responces = streamReaders.ReadToEnd();
streamResponse.Close();
streamReaders.Close();
response.Close();
}
catch(Exception ex)
{
}
}
As far as i know notFound exceptions comes when we are not posting any data while using the POST request method. you can see i have mentioned the data i am passing into the GEtRequestStreamCallback. I have mentioned a note. Please help me. Where i am going to wrong.
Try setting the content-type to application/json; charset=utf-8
Also, you can do all that stuff in nicer and shorter way(sample):
var wc = new WebClient();
//SET AUTH HEADER IF NECESSARY
//wc.Headers["Authorization"] = "OAUTH "+TOKEN;
wc.Headers["Content-Type"] = "application/json;charset=utf-8";
wc.UploadStringCompleted += (s, er) =>
{
if (er.Error != null) MessageBox.Show("Error\n" + er.Error);
else MessageBox.Show(er.Result);
};
string data = JsonConvert.SerializeObject(MY_DATA_OBJECT);
MessageBox.Show(data);
wc.UploadStringAsync(new Uri(POST_URI), "POST", data);
I did it with the help of HttpClient inplace of WebClient. Following few lines will do magic. :)
HttpClient hc = new HttpClient();
hc.BaseAddress = new Uri(annotation_url.ToString());
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, myUrl);
HttpContent myContent = req.Content = new StringContent(myJsonString, Encoding.UTF8, "application/json");
var response = await hc.PostAsync(myUrl, myContent);
//Line for pull out the value of content key value which has the actual resposne.
string resutlContetnt = response.Content.ReadAsStringAsync().Result;
DataContractJsonSerializer deserializer_Json = new DataContractJsonSerializer(typeof(MyWrapperClass));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resutlContetnt.ToString()));
AnnotateResponse = deserializer_Json.ReadObject(ms) as MyWrapperClass;

HttpClient dosen't get data after update WP8

I have this code to get JSON data from an API for WP8:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(mainURL.ToString());
HttpResponseMessage response = await client.GetAsync("");
string res = await response.Content.ReadAsStringAsync();
var root = await JsonConvert.DeserializeObjectAsync<Rootobject>(res);
Everything works perfectly, but when I update data on the web API from the web site and try to retrieve data again using this code it gets the old data even though accessing the URL in a browser it gets the new data.
When I debug line by line, I see that the "response" object contains the old data.
The only way I have found to fix this is to rebuild the project in this way it works.
How can I properly get the updated data?
There may be some caching involved. Tried adding some random string to the URL, like
client.BaseAddress = new Uri(mainURL.ToString()+"&random="+DateTime.Now.Ticks);
I have same kind of problem. I tried this this may be help you.
HttpWebRequest request = HttpWebRequest.CreateHttp(mainURL.ToString());
request.Method = "GET or Post";
request.BeginGetResponse(ResponseCallBack, request);
void ResponseCallBack(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
using (Stream data = response.GetResponseStream())
{
using (var reader = new StreamReader(data))
{
string jsonString = reader.ReadToEnd();
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Rootobject));
Rootobject yourdata= dataContractJsonSerializer.ReadObject(memoryStream) as Rootobject;
}
}
}