Cannot convert Newtonsoft.Json.JsonConverter - c#

public async Task<IActionResult> SiparisEkle(int userID, [FromQuery] int[] productIDs, [FromQuery] short[] quantities)
{
using (var httpClient = new HttpClient())
{
StringContent content = new StringContent(JsonConvert.SerializeObject(userID, productIDs, quantities), Encoding.UTF8, "application/json");
using (var cevap = await httpClient.PutAsync($"{uri}/api/Order/SiparisEkle", content))
{
string apiCevap = await cevap.Content.ReadAsStringAsync();
}
}
return RedirectToAction("Index");
}
How can I go about fixing this error?
[HttpPost]
public async Task<IActionResult> SiparisEkle(int userID, [FromQuery] int[] productIDs, [FromQuery] short[] quantities)
{
Order newOrder = new Order();
newOrder.UserID = userID;
newOrder.Status = Status.Pending;
newOrder.isActive = true;
using (var httpClient = new HttpClient())
{
StringContent content = new StringContent(JsonConvert.SerializeObject(newOrder), Encoding.UTF8, "application/json");
using (var cevap = await httpClient.PutAsync($"{uri}/api/Order/SiparisEkle", content))
{
string apiCevap = await cevap.Content.ReadAsStringAsync();
}
}
return RedirectToAction("Index");
}
This is how it is last. This is how I solved my problem

Have you tried instantiating the 'content' object on a separate line and then trying to set it, like so:
StringContent content = new StringContent();
content = JsonConvert.SerializeObject(userID, productIDs, quantities);
Apologies if that's an unhelpful suggestion. I cannot see the StringContent class so I do not know if you need it in one due to a constructor in the class. For more help, here is the NewtonSoft documentation about Serializing and Deserializing. https://www.newtonsoft.com/json/help/html/SerializingJSON.htm#JsonSerializer

Related

c# redirect post request

Trying to make a post request from one application to another using the same Form Data parameters that the first one received.
both application controller currently have same method:
public async Task<ActionResult> TestSet()
{
var inputString = Request.Form["inputString"];
var inputFile = Request.Files[0];
var resultString = await _service.Set(inputString, inputFile.FileName, inputFile.ContentType, inputFile.InputStream);
return new MyJsonResult(new
{
fileName = resultString
});
}
which return json string:
{"fileName": "someFileName.png"}
Trying to make the first method to be something like this
public async Task<ActionResult> TestSet()
{
var inputString = Request.Form["inputString"];
var inputFile = Request.Files[0];
if (!string.IsNullOrEmpty(_redirectUrl))
{
using (var client = new HttpClient())
{
HttpContent content = GetContentSomehow(this.Request); // this i have an issue with
var response = await client.PostAsync(_redirectUrl, content);
var responseString = await response.Content.ReadAsStringAsync();
return new MyJsonResult(responseString);
}
}
var resultString = await _service.Set(inputString, inputFile.FileName, inputFile.ContentType, inputFile.InputStream);
return new MyJsonResult(new
{
fileName = resultString
});
}
This could help to get ByteArrayContent for File only.
And this would probably work to get the non-file parameters into StringContent, but how to get both of them into single Content?
var jsonString = JsonConvert.SerializeObject(Request.Form.ToDictionary());
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
Solved this issue by cominig StringContent and StreamContent into MultipartFormDataContent
public static MultipartFormDataContent GetMultipartFormData(HttpRequestBase req)
{
var formData = new MultipartFormDataContent();
//formData.Headers.ContentType.MediaType = "multipart/form-data";
foreach (var row in req.Form.ToDictionary())
{
formData.Add(new StringContent(row.Value), row.Key);
}
var file = req.Files[0];
StreamContent fileStreamContent = new StreamContent(file.InputStream);
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);
formData.Add(fileStreamContent, file.FileName, file.FileName);
return formData;
}

Passing a string value as a parameter HttpClient Post

I need to pass a string value as text in a Post.
I have tried the following
string content = "91237932,xy91856,0,0";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(ConfigurationManager.AppSettings["AttributesApi"] + $"/api/UserProfiles/UpdateUserProfileFromIAM", new StringContent(content));
This is what I have to work with (can't change it as is existing) but the value is null
[HttpPost("UpdateUserProfileFromIAM")]
public async Task<ActionResult> UpdateUserProfileFromIAM(string attributes)
{
//attributes null
}
How can do this HttpClient post so that it is a simple string value?
If your issue is that you can't read the result then try this:
public async Task<string> GetData()
{
string content = "91237932,xy91856,0,0";
using var client = new HttpClient();
var response = await client.PostAsync(ConfigurationManager.AppSettings["AttributesApi"] + $"/api/UserProfiles/UpdateUserProfileFromIAM", new StringContent(content));
return await response.Content.ReadAsStringAsync();
}

Even with a successful access Token I get a 401 unauthorized in my Get() async method?

Currently I have to async methods Post() & Get(). For my Post() method is returning a access token and if you look at the bottom of my post method I am calling my Get() in there also, for the simple reason of being able to call string result in my get. but even with a successful access token I Keep getting a 401 unauthorized Status code, why?
Click to view error in VS
namespace APICredential.Controllers
{
[RoutePrefix("api")]
public class ValuesController : ApiController
{
[HttpGet, Route("values")]
public async Task<string> Post()
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("https://api.elliemae.com/oauth2/");
var parameters = new Dictionary<string, string>()
{
{"grant_type", "password"}, //Gran_type Identified here
{"username", "admin#encompass:BE11200822"},
{"password", "Shmmar****"},
{"client_id", "gpq4sdh"},
{"client_secret", "dcZ42Ps0lyU0XRgpDyg0yXxxXVm9#A5Z4ICK3NUN&DgzR7G2tCOW6VC#HVoZPBwU"},
{"scope", "lp"}
};
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "v1/token")
{
Content = new FormUrlEncodedContent(parameters)
};
HttpResponseMessage response = await client.SendAsync(request);
string resulted = await response.Content.ReadAsStringAsync();
await Get(resulted);
return resulted;
}
}
[HttpGet, Route("values/get")]
public async Task<string> Get(string resulted)
{
string res = "";
using (var client = new HttpClient())
{
// HTTP POST
client.BaseAddress = new Uri("https://api.elliemae.com/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("/encompass/v1/loans/{ea7c29a6-ee08-4816-99d2-fbcc7d15731d}?Authorization=Bearer "+resulted+"&Content-Type=application/json").Result;
using (HttpContent content = response.Content)
{
// ... Read the string.
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
}
}
return res;
}
The following is missing:
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Accesstoken);
This is your default header once you insert this then you have premission to getstring data from whatever your URL is...
code will look like this:
public async Task<string> Get(string Accesstoken)
{
string res = "";
using (var client = new HttpClient())
{
Accesstoken = Accesstoken.Substring(17, 28);
client.BaseAddress = new Uri("https://api.elliemae.com/");
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Accesstoken);
var response = client.GetAsync("encompass/v1/loans/ea7c29a6-ee08-4816-99d2-fbcc7d15731d").Result;
using (HttpContent content = response.Content)
{
// ... Read the string.
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
}

Post MultipartFormDataContent from Controller Action Method to WebApi Post method

In my ASP.NET MVC project, I am trying to post image from Controller action method to API controller method. Plan is to leverage this API to other clients to use to upload images.
I am able to successfully hit the API Post method from Controller Action method, but am not able to pass the image object.
Here is my HomeController.cs Upload Action Method
[HttpPost]
public async Task<ActionResult> Upload(FormCollection formCollection)
{
var baseUri = "http://localhost/api/Process";
HttpPostedFileBase file = Request?.Files[0];
if (file == null || (file.ContentLength <= 0) || string.IsNullOrEmpty(file.FileName))
return new EmptyResult();
string fileName = file.FileName;
byte[] fileBytes = new byte[file.ContentLength];
HttpContent stringContent = new StringContent(fileName);
HttpContent fileStreamContent = new StreamContent(file.InputStream);
HttpContent bytesContent = new ByteArrayContent(fileBytes);
using (var formDataContent = new MultipartFormDataContent())
{
formDataContent.Add(stringContent, "fileName", fileName);
formDataContent.Add(fileStreamContent, "inputStream", fileName);
formDataContent.Add(bytesContent, "fileBytes", fileName);
using (var httpClient = new HttpClient())
{
formDataContent.Headers.ContentType =
MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = await httpClient.PostAsync(baseUri, formDataContent);
var content = await response.Content.ReadAsStringAsync();
//Handle the response
}
}
return View("Result");
}
In my Process controller which is inheriting from ApiController, I have the following Post method
[HttpPost]
public async Task<string> Post([FromBody]MultipartFormDataContent formDataContent)
{
Task<string> imageContent = Request.Content.ReadAsStringAsync();
string body = imageContent.Result;
ImageResponse imageResponse = null;
//.................
//.................
return someValue
}
Here parameter formDataContent is always null and Request.Content.ReadAsStringAsync() is empty
Try sending from the Controller like this
//...other code removed for brevity
using (var form = new MultipartFormDataContent()) {
var stringContent = new StringContent("fileToUpload");
form.Add(stringContent, "fileToUpload");
var streamContent = new StreamContent(file.InputStream);
streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(file.ContentType);
streamContent.Headers.ContentLength = file.ContentLength;
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") {
Name = "fileToUpload",
FileName = file.FileName
};
form.Add(streamContent);
using (var httpClient = new HttpClient()) {
var response = await httpClient.PostAsync(baseUri, form);
//...other code removed for brevity
}
}
And then process it in the ApiController by extracting the information sent ...
[HttpPost]
public async Task<IHttpActionResult> Post() {
var content = Request.Content;
//get file name from content disposition
var fileName = content.Headers.ContentDisposition.FileName;
//Get file stream from the request content
var fileStream = await content.ReadAsStreamAsync();
//...other code removed for brevity
return Ok();
}
Referenced this answer : Upload image using HttpClient

Return a StringContent from async

How do I return a StringContent from async? Do I still need to return it as a task? Below is the sample code that I am using:
public async Task<HttpResponseMessage> GetOrder(string url)
{
xml = "<result><success> True </success><message></result>";
responseMessage = await httpContent;
return new HttpResponseMessage()
{
Content = new StringContent(xml, Encoding.UTF8, "application/xml")
};
}
If you are not actually using async/await then the method would look like this.
public Task<HttpResponseMessage> GetOrder(string url) {
xml = "<result><success> True </success><message></result>";
var responseMessage = new HttpResponseMessage() {
Content = new StringContent(xml, Encoding.UTF8, "application/xml")
};
return Task.FromResult(responseMessage);
}
Is this what you are trying to do?
public async Task<HttpResponseMessage> GetOrder(string url)
{
string xml = "<result><success> True </success><message></result>";
return await Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage()
{
Content = new StringContent(xml, Encoding.UTF8, "application/xml")
});
}
if so your return xml is also invalid. To quote one of the many online xml validators "The element type "message" must be terminated by the matching end-tag " (message)

Categories