On the controller Put is as following:
[HttpPut]
[ActionName("putname")]
public JsonResult putname(string name)
{
var response = ...
return Json(response);
}
The issue is on the when consuming this API via following
using (httpClient = new HttpClient())
{
string name = "abc";
string jsonString = JsonConvert.SerializeObject(name);
var requestUrl = new Uri("http:...../controller/putname/");
using (HttpContent httpContent = new StringContent(jsonString))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = httpClient.PutAsync(requestUrl, httpContent).Result;
}
This code doesn't pass the parameter name to controller. I even tried changeing uri to /putname/" + name.
Here is what works for me:
var jsonString = "{\"appid\":1,\"platformid\":1,\"rating\":3}";
var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
var message = await _client.PutAsync(MakeUri("App/Rate"), httpContent);
Assert.AreEqual(HttpStatusCode.NoContent, message.StatusCode);
and my action method:
public void PutRate(AppRating model)
{
if (model == null)
throw new HttpResponseException(HttpStatusCode.BadRequest);
if (ModelState.IsValid)
{
// ..
}
}
and the model
public class AppRating
{
public int AppId { get; set; }
public int PlatformId { get; set; }
public decimal Rating { get; set; }
}
-Stan
For me it worked correctly:
string requestUrl = endpointUri + "/Files/";
var jsonString = JsonConvert.SerializeObject(new { name = "newFile.txt", type = "File" });
HttpContent httpContent = new StringContent(jsonString);
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue ("application/json");
HttpClient hc = new HttpClient();
//add the header with the access token
hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
//make the put request
HttpResponseMessage hrm = (await hc.PostAsync(requestUrl, httpContent));
if (hrm.IsSuccessStatusCode)
{
//stuff
}
Related
Below is my JSON response from PHP Web API. I need this "tradeType" to be loaded in WPF ComboBox after checking "success"is true/false, If false display Error message shown in "message"
{
"success":"true",
"message":"Trade Type List",
"tradeType":[
{"id":1, "name":"Coaching Class"},
{"id":2,"name":"Food Supply"},
{"id":3,"name":"Marriage Bureau"}
]
}
I am new to WPF and Web API, what i have tried is
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://offline.localhost.in/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/utilities/trade_types").Result;
if (response.IsSuccessStatusCode)
{
var jsonString = response.Content.ReadAsStringAsync();
Root myDeserializedClass = JsonConvert.DeserializeObject<List<TradeType>>(jsonString);
cmbTrade.ItemsSource = users;
}
else
{
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
}
var jsonString = response.Content.ReadAsStringAsync();
You are missing an await here so the call is fired but not awaited. Also have Task in var instead the string.
var jsonString = await response.Content.ReadAsStringAsync();
or use the non-async version.
public class TradeType
{
public int id { get; set; }
public string name { get; set; }
}
public class Root
{
public string success { get; set; }
public string message { get; set; }
public List<TradeType> tradeType { get; set; }
}
private void GetData()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://offline.localhost.in/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/utilities/trade_types").Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(result);
myDeserializedClass.tradeType.Insert(0, new TradeType { id = 0, name = "-Select-" });
cmbTrade.ItemsSource = myDeserializedClass.tradeType;
cmbTrade.DisplayMemberPath = "name";
cmbTrade.SelectedValuePath = "id";
cmbTrade.SelectedIndex = 0;
}
else
{
MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);
}
}
I'm doing a POST method to an end point with a PDF that is converted to base64 but I'm receiving a HTTP 406 CODE. I included in the body the application/pdf for mime type and I included the necessary header to accept my POST request but still I'm receiving the 406 code. Does the json body has any connection on receiving the 406 code or am I having a problems on my header? Please see attached image for the details of the end point and json body.
public class MyFile
{
[JsonProperty("mime")]
public string MimeType { get; set; }
[JsonProperty("data")]
public string Base64Data { get; set; }
}
public class PdfFile
{
[JsonProperty("file")]
public MyFile myFile { get; set; }
}
string pdfBase64;
const string pdfFileName = "file.pdf";
using (var pdfStream = await FileSystem.OpenAppPackageFileAsync(pdfFileName))
{
using (var pdfReader = new StreamReader(pdfStream))
{
var fileContents = await pdfReader.ReadToEndAsync();
pdfBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(fileContents));
}
}
var file = new MyFile();
var pdf = new PdfFile();
file.MimeType = "application/pdf";
file.Base64Data = "base64-data=" + pdfBase64;
pdf.myFile = file;
var jsonContent = JsonConvert.SerializeObject(pdf.myFile);
string baseUrl = "https://goodmorning-axa-dev.azure-api.net/upload";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders
.Accept
.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, baseUrl);
requestMessage.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
requestMessage.Headers.Add("x-axa-api-key", apiKey);
HttpResponseMessage responseMessage = await httpClient.SendAsync(requestMessage);
string responseAsString = await responseMessage.Content.ReadAsStringAsync();
if (responseAsString != null)
{
Console.WriteLine(responseAsString);
}
I'm working on an App in Xamarin.Forms. I want to send the Post Request to an API with form-data. In the code below, it returns the success message, but the data isn't posted there.
public class Post {
public string ConnectionId { get; set; }
public string HolderFirstName { get; set; }
}
public async void SendProof(object sender, EventArgs e) {
try {
Uri URL = new Uri(string.Format("http://11.222.333.44:4000/api/v1/Proof/SendProofNameRequest"));
HttpClient _client = new HttpClient();
var post = new Post {ConnectionId = "9c12dba2-6cb9-4382-8c96-f1708a7e8816", HolderFirstName = "Carl Dreyer"};
var content = JsonConvert.SerializeObject(post);
var response = await _client.PostAsync(URL, new StringContent(content, Encoding.UTF8, "multipart/form-data"));
if (response.IsSuccessStatusCode) {
await DialogService.AlertAsync("Credential Proof Sent Successfully!");}
}
catch(Exception error) {
await DialogService.AlertAsync(error.Message); }
}
Binding for Button which triggers this Function.
public ICommand SendProofCommand => new Command(() => SendProof(default, default));
public async Task SendProof()
{
try {
HttpClient client = new HttpClient(new NativeMessageHandler());
client.BaseAddress = new Uri("http://11.222.333.44:4000/");
var postData = new List<KeyValuePair<string, string>>();
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("ConnectionId", "9c12dba2-6cb9-4382-8c96-f1708a7e8816"));
nvc.Add(new KeyValuePair<string, string>("HolderFirstName", "Bergman"));
var req = new HttpRequestMessage(HttpMethod.Post, "http://11.222.333.44:4000/" + "api/v1/Proof/SendProofNameRequest") { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
if (res.IsSuccessStatusCode)
{
await DialogService.AlertAsync("Proof Sent Successfully!");
}
else
{
await DialogService.AlertAsync("Unsuccessfull!");
}
}
catch(Exception error) {
await DialogService.AlertAsync(error.Message);
}
}
I am trying to get the html content from the news site https://nayapatrikadaily.com/news-article/2/News,
with the Http Post Request.
However in the response, page is returning the Unicode characters.
I am obstructed in converting the Unicode characters to html.
URL:
var nayapatrika = await ApiClient.PostAsync("https://nayapatrikadaily.com/ajax/pagination.php");
PostAsync:
public static async Task<HtmlDocument> PostAsync(string uri)
{
string responseJson = string.Empty;
var htmlDocument = new HtmlDocument();
var handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
var content = new MultipartFormDataContent();
var values = new[]
{
new KeyValuePair<string, string>("perPage", "20"),
new KeyValuePair<string, string>("page", "2"),
new KeyValuePair<string, string>("cat", "1"),
};
foreach (var keyValuePair in values)
{
content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
}
var response = await client.PostAsync(uri, content);
if (response.IsSuccessStatusCode)
{
responseJson = await response.Content.ReadAsStringAsync();
htmlDocument.LoadHtml(responseJson);
}
}
return htmlDocument;
}
On response the page is always returning with the below characters.
Deserializing the api response did the trick for me. As i noticed the responses it has two attributes: newsList and numPages.
I created the class: ResponseObj
public class ResponseObj
{
public string numPage { get; set; }
public string newsList { get; set; }
}
and deserliazed into ResponseObj
var obj = JsonConvert.DeserializeObject<ResponseObj>(responseJson);
var response = await client.PostAsync(uri, content);
if (response.IsSuccessStatusCode)
{
responseJson = await response.Content.ReadAsStringAsync();
var obj = JsonConvert.DeserializeObject<ResponseObj>(responseJson);
htmlDocument.LoadHtml(obj.newsList);
}
I need to call a WebApi using WebClient where have to pass an object as parameter. I have my WebApi method as similar to bellow code:
example URI: localhost:8080/Api/DocRepoApi/PostDoc
[HttpPost]
public string PostDoc (DocRepoViewModel docRepo)
{
return string.enpty;
}
and then DocRepoViewModel is:
public class DocRepoViewModel
{
public string Roles { get; set; }
public string CategoryName { get; set; }
public List<AttachmentViewModel> AttachmentInfo { get; set; }
}
AttachmentViewModel is:
public class AttachmentViewModel
{
public string AttachmentName { get; set; }
public byte[] AttachmentBytes { get; set; }
public string AttachmentType { get; set; }
}
New I need to call PostDoc method from my MVC controller (not javascript ajax). How can I pass this specific parameter that I can make the call and get all data in my WebApi method. Can we do it by WebClient? Or there are better way. Please help.
You could use the PostAsJsonAsync method as follows:
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("localhost:8080/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var docViewModel = new DocRepoViewModel() { CategoryName = "Foo", Roles= "role1,role2" };
var attachmentInfo = new List<AttachmentViewModel>() { AttachmentName = "Bar", AttachmentType = "Baz", AttachmentBytes = File.ReadAllBytes("c:\test.txt" };
docViewModel.AttachmentInfo = attachmentInfo;
response = await client.PostAsJsonAsync("DocRepoApi/PostDoc", docViewModel);
if (response.IsSuccessStatusCode)
{
// do stuff
}
}
}
Asp .net reference
Check out following code.
string url = "Your Url";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.KeepAlive = false;
request.ContentType = "application/json";
request.Method = "POST";
var entity = new Entity(); //your custom object.
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(entity));
request.ContentLength = bytes.Length;
Stream data = request.GetRequestStream();
data.Write(bytes, 0, bytes.Length);
data.Close();
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string message = reader.ReadToEnd();
var responseReuslt = JsonConvert.Deserialize<YourDataContract>(message);
}
}