I'm having trouble figuring out what's wrong with HttpClient script.
When I use Fiddler, it works & AspNetCore MVC isn't throwing errors.
http://localhost:6004/api/XUnitExamplesTest/JsonStringMethod
Http-Get
User-Agent: Fiddler
Accept: text/json
Content-Type: text/json
Host: localhost:6004
Content-Length: 24
"{\"Color\": \"Green\"}"
But HttpClient script causing AspNetCore MVC issues.
var sampleData = new XUnitSampleData() { Color = "Red" };
var contentType = "text/json";
var httpMethod = HttpMethod.Get;
var uriPath = "JsonStringMethod";
var jsonData = JsonConvert.SerializeObject(_sampleData, Formatting.None).ToString(); // JSON String. --> "{ \"Vin\" : \"foo\", \"Color\" : \"foo\" }"
var jsonRequest = string.Format("\"{0}\"", jsonData);
var result = await XUnitWebClient.GetAsync3(contentType, httpMethod, uriPath, jsonRequest, CancellationToken.None);
public static async Task<string> GetAsync3(string contentType, HttpMethod httpMethod, string uriPath, string request, CancellationToken cancellationToken)
{
using (var httpClient = new HttpClient())
{
using (var httpRequestMessage = new HttpRequestMessage(httpMethod, string.Format("{0}{1}", _uri, uriPath)))
{
httpClient.BaseAddress = new Uri(string.Format("{0}", _baseAddress));
//httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType)); // "Accept" Header.
//httpClient.DefaultRequestHeaders.Remove("Content-Type");
//httpClient.DefaultRequestHeaders.Add("Content-Type", contentType);
httpRequestMessage.Content = new StringContent(request, Encoding.UTF8, contentType); // "Content-Type" Header.
var response = await httpClient.SendAsync(httpRequestMessage);
return await response.Content.ReadAsStringAsync();
}
}
}
AspNetCore MVC got the JSON value as "{".
Since I'm using text/json so how do I tell HttpClient to send json string with beginning quote and ending quote, instead of it stripping that out?
Or am I doing something wrong with JsonConvert.SerializeObject() here?
To answer the question directly...
You're not escaping the quotes inside the JSON string. Try this:
var jsonRequest = string.Format("\"{0}\"", jsonData.Replace("\"", "\\\""));
However...
I question how you're approaching this problem. You mention in your comments that you get an error on the server side (in your MVC code) if you don't stringify the JSON on the client side. However, it is very awkward and non-standard to require the client to do this. I would:
Change the content type from text/json to application/json. That won't fix the problem, but it is the standard.
Remove the line above and send jsonData directly. i.e. don't stringify the JSON.
Ask a new question about how to solve the server-side error you're getting, and post the relevant MVC code.
Related
I cannot add Content-type as "application/x-www-form-urlencoded". There is throwing an error. Only for the this content-type. Thank You for the attention.
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = new HttpMethod("POST"),
RequestUri = new Uri(path),
};
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response1 = await httpClient.SendAsync(request);
var token = await response1.Content.ReadAsStringAsync();
}
It's throwing error like that
"Misused header name, 'Content-Type'. Make sure request headers are
used with HttpRequestMessage, response headers with
HttpResponseMessage, and content headers with HttpContent objects."
The content type is a header of the content, not of the request, which is why this is failing.
One way is that you can call TryAddWithoutValidation instead of add like below:
request.Headers.TryAddWithoutValidation("Accept", "application/json");
request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
The other way is that you can set the Content-Type when creating the request content itself, refer to this answer.
I'v used something more complicated but it works.
var client = new HttpClient();
//headers dictionary
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");
//request
var req = new HttpRequestMessage(HttpMethod.Post, new Uri(url)) { Content = new FormUrlEncodedContent(dict) };
req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencode"));
var response = await client.SendAsync(req);
I'm having a hard time executing a http get call with headers to an api with oauth2 authorization.
I already tried the code below but then I'm receiving an Unauthorized response from the api. I think the problem is that because I've executed the GETASYNC() without the adding some headers. Can you help me to find a way on how to add headers before I execute the GETASYNC().
public HttpClient webApiClient = new HttpClient();
public async System.Threading.Tasks.Task<ActionResult> Index()
{
var uri = new Uri("https://myURL.com/"+ transno);
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var response = await webApiClient.GetAsync(uri);
response.Headers.Add("Accept", "application/json");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.Headers.Add("client-id", "clientid");
response.Headers.Add("client-secret", "clientsecret");
response.Headers.Add("partner-id", "partnerid");
var result = JObject.Parse(await response.Content.ReadAsStringAsync());
}
In ASP.Net Core 2.0, how can I POST data while redirecting to a third-party URL using Response.Redirect()?
Note: I have to POST this data without using the query-string.
Response.Redirect triggers a GET request which means that the only option is using a query string.
Can you trigger the redirection from the client (if any) in order to make a POST request?
You must use object if you want post data without using query string.
[HttpPost]
public IActionResult Search([FromBody] CustomerSearchRequestApiModel request)
{
if (request == null)
{
return BadRequest();
}
return Ok(request);
}
It is impossible to use Response.Redirect() to send Post request.
For a workaround, you could try HttpClient to send Post request and then return the reponse to the web browser with ContentResult as text/html.
Here is a demo code:
public async Task<ContentResult> HtmlView()
{
using (var formDataContent = new MultipartFormDataContent())
{
HttpClient client = new HttpClient();
Article article = new Article { ArticleName = "AN" };
formDataContent.Add(new StringContent("AN", Encoding.UTF8, "application/json"), "ArticleName");
using (HttpClient httpClient = new HttpClient())
{
HttpResponseMessage response = await httpClient.PostAsync(#"https://localhost:44393/Articles/Create", formDataContent);
return new ContentResult
{
ContentType = "text/html",
StatusCode = (int)response.StatusCode,
Content = await response.Content.ReadAsStringAsync()
};
}
}
}
Note
Change the HttpClient part to send the right request to your own third party url with validate parameters.
I am calling a .NET WebApi2 endpoint from a dotnet core webapi. When I debug into the .NET WebApi2 POST endpoint, my value is always null. Is this not possible to do?
When I call the GET endpoint with an ID, the ID is passed with no issues.
I have used both Postman and Fiddler to debug. Whenever I pass my JSON object from Postman to the .NET WebApi2 POST endpoint, my value is populated.
Beyond frustrated as this seems pretty simple. :,(
Updated to include code
dotnet core web api (calling from Postman)
[HttpPost]
public async Task PostAsync([FromBody] string value)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var jsonObject = new JObject();
jsonObject.Add("text", "Rich");
var response = await client.PostAsJsonAsync("http://localhost:54732/api/Rich", jsonObject);
var responseResult = response.Content.ReadAsStringAsync().Result;
}
.NET WebApi2 (JObject is always null)
// POST: api/Rich
public void Post(JObject value)
{
}
This boils down to using JObject basically. For your older Web Api action, JObject works merely because you're posting JSON, and JObject is a dynamic. However, that is an entirely incorrect approach. You should be binding to a concrete class that represents the JSON being posted. That said, you may or may not be able to change anything there, and its not technically the source of your current issue.
The actual source is that you're attempting to send a JObject, which is not doing what you think it is. Again, JObject is a dynamic. It has accessors to parse and access the underlying JSON, but it does not actually expose the members of that JSON object directly. As a result, if you attempt to serialize it, you won't get anything usable from it. Passing it to PostAsJsonAsync causes it to be serialized.
What you actually need is something like:
var jsonObject = new { text = "Rich" };
Then, what you're passing to PostAsJsonAsync will be an anonymous object with actual members that can be serialized.
My "REAL" issue turned out to be Transfer-Encoding: chunked was being sent in the request header.
Here is my corrected code (dotnet core web api):
public async Task PostAsync([FromBody] JObject value)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
var jsonObject = new { variable1 = "Rich" };
var json = JsonConvert.SerializeObject(jsonObject);
var content = new StringContent(json, Encoding.UTF8, "application/json");
content.Headers.ContentLength = json.Length;
var response = await client.PostAsync("http://localhost:54732/api/Rich", content);
var responseResult = response.Content.ReadAsStringAsync().Result;
}
Here is my .NET WebApi2 code:
public IHttpActionResult Post([FromBody]RichTest value)
{
return Ok(value.variable1 + " done");
}
public class RichTest
{
public string variable1 { get; set; }
}
When I set the content.Headers.ContentLength, the Transfer-Encoding: chunked is removed. Now my code is working!!
I am still curious why the original PostAsJsonAsync does not work...
I am trying to develop twitter client. i am using RestSharp for api. its work fine with authentication and gettimeline but its give error when i try to search twitter with # hashtag . its gives error like bad request and unauthorized.
Working code
public string GetTimeLine(string key,string secret,string userToken,string userSecret)
{
var request = new RestRequest("/1.1/statuses/user_timeline.json", Method.GET);
Client.Authenticator = OAuth1Authenticator.ForProtectedResource(key, secret, userToken, userSecret);
var response = Client.Execute(request);
return response.Content;
}
Respond with unauthorized error:
public string GetHashtag(string key, string secret, string userToken, string userSecret)
{
var request = new RestRequest("/1.1/search/tweets.json?q=%23freebandnames", Method.GET);
Client.Authenticator = OAuth1Authenticator.ForProtectedResource(key, secret, userToken, userSecret);
var response = Client.Execute(request);
return response.Content;
}
Try this:
var request = new RestRequest("/1.1/search/tweets.json?q={query}", Method.GET);
request.AddUrlSegment("query", "#freebandnames");