i had created a code to insert a product item into my API, but its not working, i had tried to do manually using the PostMan and just made it, the status is allways 201 - created, im using .net 6
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
using WebApplication1.Data;
using WebApplication1.Models;
using (var httpClient = new HttpClient())
{
Item_Produtos item = new Item_Produtos();
item.Id = 10;
item.Produto_Id = 109;
item.PedidoVenda_Id = 15283;
item.qtdItem = 1;
item.vlPreco = 109;
item.Item_Obs = "";
item.Opcao_Obs = "Tamanho:M=1;|Cor:Especial=1;|";
item.Store_Id = 27;
item.vlSubTotal = 109;
using HttpClient client = new()
{
BaseAddress = new Uri("api/adress-here")
};
HttpResponseMessage response = await client.PostAsJsonAsync("carrinho", item);
Console.WriteLine(
$"{(response.IsSuccessStatusCode ? "Success" : "Error")} - {response.StatusCode}");
} ```
I solved my problem by separating some steps, at first converting into a Json then into a string Content, and then instead of use the PostAsJsonAsync i used the PostAsync with the new format
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
using WebApplication1.Data;
using WebApplication1.Models;
using System.Text;
using HttpClient client = new(){
BaseAddress = new Uri("api/adress-here")
};
var json = JsonSerializer.Serialize(item);
var data = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("carrinho", data);
Related
I send a request on the API, the request and the response are successful, but I want to get the value equivalent to the authentication keyword through the response. How can I do that? I tried this way on the examples I found, but it doesn't give any results .Net 6.0
using LoggerApi.Login;
using System;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using System.Linq;
using Microsoft.Extensions.Primitives;
namespace LoggerApi.Login
{
public class AdminLogin
{
public async static Task<object> GetAuthenticationCode()
{
var client = new HttpClient();
var loginEndpoint = new Uri("https://admin.com/login");
var loginPayload = new LoginPayload()
{
Username = "admin",
Password= "admin",
};
var requestJson = JsonConvert.SerializeObject(loginPayload);
var payload = new StringContent(requestJson, Encoding.UTF8, "application/json");
var res = await client.PostAsync(loginEndpoint, payload).Result.Headers.TryGetValues("authentication");
return res;
}
}
}
I want to query GitHub repository and issues using GraphQL and C#. When I query GitHub repository and issues, VS Code keeps erroring out error CS1003: Syntax error, ',' expected. If I replace the repository query with a simple query(viewer{login}), it works fine.
using GraphQL;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Net.Http.Headers;
class Program
{
static async Task Main(string[] args)
{
var httpClient = new HttpClient
{
BaseAddress = new Uri("https://api.github.com/graphql")
};
httpClient.DefaultRequestHeaders.Add("User-Agent", "MyConsoleApp");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "MyPersonalToken");
var queryObject = new
{
query = #"
query {
repository(owner:"BT23", name:"demo-repo"){
issues(last:10){
edges{
node{
title
}
}
}
}
}",
variables = new { }
};
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content = new StringContent(JsonConvert.SerializeObject(queryObject), Encoding.UTF8, "application/json")
};
dynamic responseObj;
using (var response = await httpClient.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
responseObj = JsonConvert.DeserializeObject<dynamic>(responseString);
}
//Console.WriteLine(responseObj.data.viewer.login);
//Console.ReadLine();
}
}
Please advise.
I am trying to post a file to an iManage server REST interface (Apache server, java backend?? not sure). Postman works fine, but when I try it from C# .NET CORE 3.1 I get a response like so:
{
"error": {
"code": "FileUploadFailure",
"message": "File upload failure"
}
}
Anyone have any ideas I can try? Thanks!
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.IO;
using System.Text;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static async Task Main(string[] args)
{
Uri url = new Uri("https://iManageServer.net/");
string filename = #"C:\Temp\temp.txt";
string token = "E4vt1DzXcnkQTmOUspN6TG6KLR7TClCPPbjyvHsu9TRlKvND9gO4xTPYIEYy0+Lu";
const string folderId = "MyFolderId";
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var content = new MultipartFormDataContent($"{DateTime.Now.Ticks:x}"))
{
var jsonString = JsonConvert.SerializeObject(new { warnings_for_required_and_disabled_fields = true, doc_profile = new { name = Path.GetFileNameWithoutExtension(filename), extension = Path.GetExtension(filename).TrimStart('.'), size = fs.Length } });
HttpContent httpContent = new StringContent(jsonString, Encoding.UTF8);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var c1 = httpContent;
content.Add(c1, "\"json\"");
var c2 = new StreamContent(fs);
c2.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
content.Add(c2, "\"file\"");
c2.Headers.ContentDisposition.FileName = $"\"{filename}\"";
c2.Headers.ContentDisposition.FileNameStar = null;
var hch = new HttpClientHandler();
hch.ServerCertificateCustomValidationCallback += (sender, cert, chain, error) => true;
using (var httpClient = new HttpClient(hch) { BaseAddress = url })
{
httpClient.DefaultRequestHeaders.Add("User-Agent", "PostmanRuntime/7.26.5");
httpClient.DefaultRequestHeaders.Add("Accept", "*/*");
httpClient.DefaultRequestHeaders.Add("Connection", "keep-alive");
using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"folders/{folderId}/documents"))
{
requestMessage.Headers.Add("X-Auth-Token", token);
requestMessage.Content = content;
var response = await httpClient.SendAsync(requestMessage);
string jsonResponse = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
//never hits
}
else
{
System.Diagnostics.Debug.WriteLine(jsonResponse);
//{
// "error": {
// "code": "FileUploadFailure",
// "message": "File upload failure"
// }
//}
}
}
}
}
}
}
}
}
Postman works fine. Here is what the Wireshark trace looks like for both:
Postman is First then the C# result:
The Boundary on the MultipartFormDataContent was quoted. The iManage API did not like that.
I had to add the following code right after the instantiation of the content:
var boundary = $"-------------------------{DateTime.Now.Ticks:x}";
content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type", $"multipart/form-data; boundary={boundary}");
content.GetType().BaseType.GetField("_boundary", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).SetValue(content, boundary);
I have written a controller to download/stream file to the clients local machine. The code doesn't stream the file on doing a GET to the url besides only produces response body.
What is the problem with streamcontent method. On debug i could not find the issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Text;
namespace FileDownloaderService.Controllers
{
[Route("api/[controller]")]
public class FileDownloadController : Controller
{
[HttpGet]
public HttpResponseMessage Get() {
string filename = "ASPNETCore" + ".pdf";
string path = #"C:\Users\INPYADAV\Documents\LearningMaterial\"+ filename;
if (System.IO.File.Exists(path)) {
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
stream.Position = 0;
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = filename };
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentDisposition.FileName = filename;
return result;
}
else
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.Gone);
return result;
}
}
}
}
Response:
{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Disposition","value":["attachment; filename=ASPNETCore.pdf"]},{"key":"Content-Type","value":["application/pdf"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}
In ASP.NET Core, you need to be using an IActionResult if you are sending a custom response. All other responses will be serialized (JSON by default) and sent as response body.
Refer to the answer at File Streaming in ASP.NET Core
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace ConsoleProgram
{
public class Class1
{
private const string URL = "https://sun.domain.com/v1/service/token";
static void Main(string[] args)
{
var handler = new HttpClientHandler();
handler.Credentials = new System.Net.NetworkCredential("admin#client", "admin");
HttpClient client = new HttpClient(handler);
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", "admin", "admin"))));
// client.BaseAddress = new Uri(URL);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// List data response.
HttpResponseMessage response = client.GetAsync(URL).Result; // Blocking call!
String res = response.ToString();
Console.WriteLine(res);
}
}
}
I am getting unauthorized error even though I am passing the correct credentials. Any ideas?
I tried almost all the answers posted on StackOverflow.
For Basic Authentication, you need to send the credentials in an authorization header called "Basic" with base64-encoded "username:password" as the value. This should get the job done:
var headerVal = Convert.ToBase64String(Encoding.UTF8.GetBytes("admin#client:admin"));
var header = new AuthenticationHeaderValue("Basic", headerVal);
client.DefaultRequestHeaders.Authorization = header;