I am using jira api to add attachment to the issue
According to documentation i have set few things.
submit a header of X-Atlassian-Token: nocheck with the request.
The name of the multipart/form-data parameter that contains attachments must be "file".
resource expects a multipart post.
& when i run my code i get internal server error.
my code is as follows
string postUrl = "http://localhost:8080/rest/api/latest/issue/TES-99/attachments";
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.DefaultRequestHeaders.Add("X-Atlassian-Token", "nocheck");
client.BaseAddress = new System.Uri(postUrl);
byte[] cred = UTF8Encoding.UTF8.GetBytes(credentials);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
var content = new MultipartFormDataContent();
var values = new[]
{
new KeyValuePair<string, string>("file", "e:\\z.txt")
};
foreach (var keyValuePair in values)
{
content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
}
var result = client.PostAsync(postUrl, content).Result;
please suggest where i am making mistake
I solved this too. now i am able to add attachment using JIRA API with C#.
i was making mistake with this piece of code.
var values = new[]
{
new KeyValuePair<string, string>("file", "e:\\z.txt")
};
foreach (var keyValuePair in values)
{
content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
}
this is my code.
string postUrl = "http://localhost:8080/rest/api/latest/issue/" + projKey + "/attachments";
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.DefaultRequestHeaders.Add("X-Atlassian-Token", "nocheck");
client.BaseAddress = new System.Uri(postUrl);
byte[] cred = UTF8Encoding.UTF8.GetBytes(credentials);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
MultipartFormDataContent content = new MultipartFormDataContent();
**//The code which solved the problem**
HttpContent fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType);
content.Add(fileContent, "file",fileName);
var result = client.PostAsync(postUrl, content).Result;
This is my working code.
[HttpPost]
public async Task<IActionResult> CreateTicketWithAttachent(IFormFile file, [FromQuery] string issuekey)
{
try
{
string url = $"http://jiraurl/rest/api/2/issue/{issuekey}/attachments";
var client = new HttpClient();
var header = new AuthenticationHeaderValue("Basic", "your-auth-key");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = header;
client.DefaultRequestHeaders.Add("X-Atlassian-Token", "no-check");
MultipartFormDataContent multiPartContent = new MultipartFormDataContent("-data-");
ByteArrayContent byteArrayContent;
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
//string fileString = Convert.ToBase64String(fileBytes);
byteArrayContent = new ByteArrayContent(fileBytes);
}
multiPartContent.Add(byteArrayContent, "file", file.FileName);
var response = await client.PostAsync(url, multiPartContent);
var result = response.Content.ReadAsStringAsync().Result;
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw new Exception(result);
return Ok();
}
catch (Exception e)
{
return BadRequest(e);
}
}
Related
i'm building a Web Application to consume A REST FULL API ASP.Net Core Web Service, i have Problem when i update a records.
i'm trying to Call Put Method from API ASP.Net core by ASP.Net Core application
I have got an NullReferenceException: Object reference not set to an instance of an object.
public async Task<IActionResult> UpdateEmployee(int id)
{
Employee employee = new Employee();
using(var httpClient=new HttpClient())
{
using(var response = await httpClient.GetAsync("myURI/employee/" + id))
{
string apiResponse = await
response.Content.ReadAsStringAsync();
employee = JsonConvert.DeserializeObject<Employee>apiResponse);
}
}
return View(employee);
}
[HttpPost]
public async Task<IActionResult> UpdateEmployee(Employee employee)
{
Employee receivedemployee = new Employee();
using(var httpClient=new HttpClient())
{
var content = new MultipartFormDataContent();
content.Add(new
StringContent(employee.EmployeeId.ToString(),Encoding.UTF8,
"application/json"), "id");
content.Add(new
StringContent(employee.FirstName,Encoding.UTF8,
"application/json"),"FirstName");
content.Add(new StringContent(employee.LastName,
Encoding.UTF8, "application/json"), "LastName");
content.Add(new StringContent(employee.DateOfBirth.ToString(),
Encoding.UTF8, "application/json"), "Email");
content.Add(new StringContent(employee.PhoneNumber,
Encoding.UTF8, "application/json"), "DateOfBirth");
content.Add(new StringContent(employee.Email, Encoding.UTF8,
"application/json"), "Email");
using (var response = await httpClient.PutAsync("myURI/api/employee", content))
{
string apiResponse = await response.Content.ReadAsStringAsync();
ViewBag.Result = "Success";
receivedemployee = JsonConvert.DeserializeObject<Employee>(apiResponse);
}
return View(receivedemployee);
}
}
}
i expected updating a record
I cleaned up your code a bit. try it this way
I removed unnecessary using blocks and serialized your employee class with a single "application/json" encoding.
public async Task<IActionResult> UpdateEmployee(int id)
{
Employee employee = new Employee();
var httpClient = new HttpClient();
var request = new HttpRequestMessage
(HttpMethod.Get, $"myURI/employee/{id}");
var response = await httpClient.SendAsync(request);
string apiResponse = await response.Content.ReadAsStringAsync();
employee = JsonConvert.DeserializeObject<Employee>(apiResponse);
return View(employee);
}
[HttpPost]
public async Task<IActionResult> UpdateEmployee(Employee employee)
{
Employee receivedEmployee = new Employee();
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Put, $"myURI/employee/{employee.EmployeeId}")
{
Content = new StringContent(new JavaScriptSerializer().Serialize(employee), Encoding.UTF8, "application/json")
};
var response = await httpClient.SendAsync(request);
string apiResponse = await response.Content.ReadAsStringAsync();
ViewBag.Result = "Success";
receivedEmployee = JsonConvert.DeserializeObject<Employee>(apiResponse);
return View(receivedEmployee);
}
I am making the below request from a WPF app to an MVC Core app that acts as an API:
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("userName", userName),
new KeyValuePair<string, string>("password", password)
});
////var content = new StringContent($"{{\"username\": {userName}, \"password\": {password}}}", Encoding.UTF8, "application/json");
var resp = await _client.PostAsync("api/Token", formContent);
var json = await resp.Content.ReadAsStringAsync();
var tw = JsonConvert.DeserializeObject<TokenWrapper>(json);
return tw.Token;
When I inspect resp with a breakpoint, after the PostAsync call, I see a 415 - Unsupported Media Type error. A breakpoint on the first line of the action isn't event hit, so I think the request isn't even reaching the controller.
The controller action looks like this:
public async Task<string> LoginAsync(string userName, string password)
{
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("userName", userName),
new KeyValuePair<string, string>("password", password)
});
////var content = new StringContent($"{{\"username\": {userName}, \"password\": {password}}}", Encoding.UTF8, "application/json");
var resp = await _client.PostAsync("api/Token", formContent);
var tempContent = await resp.Content.ReadAsStringAsync();
var json = await resp.Content.ReadAsStringAsync();
var tw = JsonConvert.DeserializeObject<TokenWrapper>(json);
return tw.Token;
}
I would expect FormUrlEncodedContent to imply the content type and work, as in the high number of examples I have seen like this. Why am I getting this 415 error?
Try by setting the Media Typeas below:
var content = new StringContent(formContent.ToString(), Encoding.UTF8, "application/json");
var result = await _client.PostAsync("http://example.com/api/Token", content);
Also PostAsync accepts parameters of requestUri and content , your code is the missing Absolute requestUri.
I have a method which convert my html in a string for export to PDF
only I need convert my html (View) to a string in order to export to PDF
Code:
public string RenderViewToString(Controller controller, string viewName, object viewData)
{
var renderedView = new StringBuilder();
using (var responseWriter = new StringWriter(renderedView))
{
var fakeResponse = new HttpResponse(responseWriter);
var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse);
var fakeControllerContext = new ControllerContext(new HttpContextWrapper(fakeContext), controller.ControllerContext.RouteData, controller.ControllerContext.Controller);
var oldContext = HttpContext.Current;
HttpContext.Current = fakeContext;
using (var viewPage = new ViewPage())
{
var html = new HtmlHelper(CreateViewContext(responseWriter, fakeControllerContext), viewPage);
html.RenderPartial(viewName, viewData);
HttpContext.Current = oldContext;
}
}
return renderedView.ToString();
}
But the value is not going to view my ViewBag:
ViewBag.Email = usuario.strUsuarioEmail;
ViewBag.Nome = usuario.strUsuarioNome;
Code Export PDF:
public ActionResult EventoVisualizarPDF()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["UrlAPI"]);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var id = Session["intCodigoGrupoUsuario"];
var intUsuarioId = Session["intUsuarioId"];
string url = "";
url = "api/usuario/GetBuscaUsuario/" + intUsuarioId;
HttpResponseMessage resposta = client.GetAsync(url).Result;
if (resposta.IsSuccessStatusCode)
{
var usuario = resposta.Content.ReadAsAsync<Usuario>().Result;
ViewBag.Email = usuario.strUsuarioEmail;
ViewBag.Nome = usuario.strUsuarioNome;
}
url = "api/evento/GetEventoByUsuario/" + id;
HttpResponseMessage response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
var eventos = response.Content.ReadAsAsync<IEnumerable<Evento>>().Result;
return this.ViewPdf("Customer report", "RelatorioEventoPDF", eventos.OrderBy(m => m.strEventoCodigo));
}
else
{
string msg = response.IsSuccessStatusCode.ToString();
throw new Exception(msg);
}
}
how do to retrieve the value from my ViewBag in view?
If you're familiar with blob storage in Azure, you can think of the ViewBag as the same abstract type of data store.
I'm assuming that you want to output these values so they can be consumed by your View -> PDF conversion method, so all you need on your view is :
<label id="vbEmail">#ViewBag.Email</label>
<label id="vbNome">#ViewBag.Nome</label>
That will output the values you've set in the controller as HTML.
My windows phone client sends a piece of JSON that represents the Name and Score... Should I be using the Class from the Web API instead ? What is the code to send the object to the server rather than the raw json?
private void btnCreateSampleScore_Click(object sender, RoutedEventArgs e)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://punkoutersoftware.azurewebsites.net");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("Bob", "2.65")
});
var result = client.PostAsync("/api/DrunkMeterScore", content).Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
Console.WriteLine(resultContent);
//DrunkMeterScore dms = new DrunkMeterScore();
//dms.Name = "Bob";
//dms.Score = 2.42;
}
}
The server is using the plain Web API template
// POST api/DrunkMeterScore
public HttpResponseMessage PostDrunkMeterScore(DrunkMeterScore drunkmeterscore)
{
if (ModelState.IsValid)
{
db.DrunkMeterScores.Add(drunkmeterscore);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, drunkmeterscore);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = drunkmeterscore.DrunkMeterScoreId }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
edit1:
I tried both of these.. They both hang and never come back during the PostAsync calls :(
var client = new HttpClient();
client.BaseAddress = new Uri("http://punkoutersoftware.azurewebsites.net");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var score = new DrunkMeterScore() { Name = "Joe", Score = 2.67 };
//MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
//HttpContent content = new ObjectContent<DrunkMeterScore>(score, jsonFormatter);
//var resp = client.PostAsync("api/DrunkMeterScore", content).Result;
//Uri scoreUri = null;
//HttpResponseMessage response = client.PostAsJsonAsync("api/DrunkMeterScore", score).Result;
//if (response.IsSuccessStatusCode)
//{
// scoreUri = response.Headers.Location;
//}
//else
//{
// Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
//}
To serialize objects you need the ObjectContent class which for the wp8 is only available as an alpha release.
Use the package console to do,
Install-Package Microsoft.AspNet.WebApi.Client -Pre
Should be something like this. I did this from memory so YMMV.
DrunkMeterScore dms = new DrunkMeterScore();
dms.Name = "Bob";
dms.Score = 2.42;
var content = new ObjectContent(dms, new JsonMediaTypeFormatter());
var result = client.PostAsync("/api/DrunkMeterScore", content).Result;
Simple requirement . I have a class - User - {userId, userName, age}.
How to serailize a object of the class and sent to a url (using post) using webclient.
Something Like below.
What is the best way to serialise user object into postdata format.
WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;
client.Credentials = CredentialCache.DefaultNetworkCredentials;
string postData = "orderId=5&status=processed2&advertId=ADV0001a";
byte[] postArray = Encoding.ASCII.GetBytes(postData);
client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
byte[] responseArray = client.UploadData(address, postArray);
var result = Encoding.ASCII.GetString(responseArray);
return result;
I would apply the following simplification to your code:
using (var client = new WebClient())
{
client.Credentials = CredentialCache.DefaultNetworkCredentials;
var data = new NameValueCollection
{
{ "userId", user.Id },
{ "userName", user.Name },
{ "age", user.Age }
};
var responseArray = client.UploadValues(address, data);
return Encoding.ASCII.GetString(responseArray);
}