I have created a web service using .NET Web API. The web service part works great, I am able to send the zip file using Advanced REST Client. The problem is that I can't send the zip file programmatically. Here is the Advanced REST Client Request Headers:
I have try some things but without success. I am not posting what I have try, considering that this is basic stuff for web developers (I am desktop developer), but if it is necessary, I will. Thank you in advance.
EDIT: This is my recent version
private async void BeginUpdate(bool webserverStatus)
{
if (!webserverStatus) return;
var httpClient = new HttpClient();
var form = new MultipartFormDataContent();
var byteArray = File.ReadAllBytes("myUpdatePackage.zip");
form.Add(new ByteArrayContent(byteArray, 0, byteArray.Length), "myUpdatePackage", "myUpdatePackage.zip");
HttpResponseMessage response = await httpClient.PostAsync(#"http://localhost:9000/api/file/", form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
}
I realized that on Advanced REST Client, I was it using PUT, meanwhile on my C# application I call it using POST
HttpResponseMessage response = await httpClient.PostAsync(#"http://localhost:9000/api/file/", form);
So, here is the complete code:
private async void BeginUpdate(bool webserverStatus)
{
if (!webserverStatus) return;
var byteArray = File.ReadAllBytes("myUpdatePackage.zip");
var httpClient = new HttpClient();
var form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(byteArray, 0, byteArray.Length), "myUpdatePackage", "myUpdatePackage.zip");
HttpResponseMessage response = await httpClient.PutAsync(#"http://localhost:9000/api/file/", form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
}
More details on this question
Related
I have a web api and a web app both written in asp.net and want to send a PDF from the api to the web app for display in a new browser window, the api is working sending the file as a streamcontent but i cannot find a way of prompting the client browser to display this in a new window, i cant make the browser make the request to the api directly as i need to add an authentication header first.
Does anyone have any ideas?
As an alternative if this is not possible i could also have the file downloaded to the client machine but i also dont know how to do that.
api code:
public HttpResponseMessage Get()
{
var response = new HttpResponseMessage();
string auth;
try
{
auth = Request.Headers.Authorization.Parameter;
}catch { return new HttpResponseMessage(HttpStatusCode.Unauthorized); }
if (auth == "test" || auth == null)
{
FileStream stream = File.OpenRead(Path.Combine(Storage.FilesDirectory, "0d23b37f-3ade-4342-beea-c6ba2cbf83cb.file"));
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
return response;
}
else return new HttpResponseMessage(HttpStatusCode.Forbidden);
}
Current client code that gets the stream but i dont know how to display that in the browser:
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, API.DocumentUrl);
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", "test");
var res = await HttpClientSingleton.Client.SendAsync(req);
I'm struggling with the following problem:
I've created a solution with the following projects: 1 MVC front-end and 2 test API's for testing my backend API broker.
In my front-end I call my API broker(which is also an API) which sends requests to my 2 test API's. I'm receiving the response of this request in my API Broker in string format and I'm trying to return this into JSON to my front-end, how do I consume this api and return the response in JSON to my front-end? Look code below:
Front-end calling my API Broker:
[HttpGet]
public async Task<ActionResult> getCall()
{
string url = "http://localhost:54857/";
string operation = "getClients";
using (var client = new HttpClient())
{
//get logged in userID
HttpContext context = System.Web.HttpContext.Current;
string sessionID = context.Session["userID"].ToString();
//Create request and add headers
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Custom header
client.DefaultRequestHeaders.Add("loggedInUser", sessionID);
//Response
HttpResponseMessage response = await client.GetAsync(operation);
if (response.IsSuccessStatusCode)
{
string jsondata = await response.Content.ReadAsStringAsync();
return Content(jsondata, "application/json");
}
return Json(1, JsonRequestBehavior.AllowGet);
}
}
My API Broker consuming one of my two test API's:
[System.Web.Http.AcceptVerbs("GET")]
[System.Web.Http.HttpGet]
[System.Web.Http.Route("RedirectApi")]
public void getCall()
{
setVariables();
WebRequest request = WebRequest.Create(apiUrl);
HttpWebResponse response = null;
response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
var srResult = sr.ReadToEnd();
sr.Close();
//Return JSON object here!
}
}
I'm also worried that my front-end is expecting a ActionResult instead of a JSON object, I hope you I find some suggestions here.
Thanks in advance!
use HttpClient for making the request which allows you to read the content as string. Your API needs to be configured so it will allow JSON responses (default behavior) and then here is an example of making a request and reading it as string which will be in JSON format (if the API returns a JSON body).
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Receiving JSON data back from HTTP request
This should be pretty straightforward, but I can't get it to work. I'm using these instructions. I've tried using the Nuget package in my PCL targeting 259 as as well as in another PCL targeting 7. Both PCLs never return after these lines. I've tried both.
//text = await client.RecognizeTextAsync(imageURL);
text = await client.RecognizeTextAsync(imageURL, languageCode: "en", detectOrientation: true);
Here is the REST code I've also tried. This works with my HTTP Helper.
public static async Task<OcrResults> PostReceiptAsync(string imageURL)
{
try
{
var apiKey = "KEY 1";
var content = await HttpHelper.Request(null, String.Format("https://eastus2.api.cognitive.microsoft.com/vision/v1.0?language=en&detectOrientation=true&subscription-key={0}&url={1}", apiKey, imageURL), null, HttpRequestType.POST);
return Mapper<OcrResults>.MapFromJson(await content.ReadAsStringAsync());
}
catch (Exception e)
{
throw;
}
}
In both methods, I'm trying to use a Blob image URL. Here is my calling method.
takePhoto.Clicked += async (sender, args) =>
{
}
It's almost seems like a deadlock issue.
Any help is much appreciated. Thanks!
UPDATE: I finally got the REST method to work with Android and UWP using this bit of code, but it fails in my iOS app. The main problem I had is that the URL that you copy out of Azure does not include the ocr? parameter. The Json Mapper is something that my SDK uses. OcrResults comes from the Project Oxford Nuget package.
public static async Task<OcrResults> ProcessReceiptAsync(string imageUrl)
{
// Instantiate a HTTP Client
var client = new HttpClient();
var apiKey = "KEY 1";
// Request parameters and URI
string requestParameters = "language=en&detectOrientation =true";
string uri = "https://eastus2.api.cognitive.microsoft.com/vision/v1.0/ocr?" + requestParameters;
// Pass subscription key thru the HTTP Request Header
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);
// Format Request body
byte[] byteData = Encoding.UTF8.GetBytes($"{{\"url\": \"{imageUrl}\"}}");
using (var content = new ByteArrayContent(byteData))
{
// Specify Request body Content-Type
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// Send Post Request
HttpResponseMessage response = await client.PostAsync(uri, content);
// Read Response body into the model
//return await response.Content.ReadAsStringAsync(OcrResults);
var result = Mapper<OcrResults>.MapFromJson(await response.Content.ReadAsStringAsync());
return result;
}
}
UPDATE 2: This method also works on Android and UWP, but fails with a BadRequest in my iOS app. I wanted to change up how the image URL gets encoded.
public static async Task<OcrResults> ProcessReceiptAsync2(string imageUrl)
{
// Instantiate a HTTP Client
var client = new HttpClient();
var apiKey = "KEY 1";
// Request parameters and URI
string requestParameters = "language=en&detectOrientation =true";
string uri = "https://eastus2.api.cognitive.microsoft.com/vision/v1.0/ocr?" + requestParameters;
// Pass subscription key thru the HTTP Request Header
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", apiKey);
// Format Request body
var dict = new Dictionary<string, string>();
dict.Add("url", imageUrl);
//var param = JsonConvert.SerializeObject($"{{\"url\": \"{imageUrl}\"}}");
var param = JsonConvert.SerializeObject(dict);
HttpContent contentPost = new StringContent(param, Encoding.UTF8, "application/json");
// Specify Request body Content-Type
//contentPost.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Send Post Request
HttpResponseMessage response = await client.PostAsync(uri, contentPost);
// Read Response body into the model
//return await response.Content.ReadAsStringAsync(OcrResults);
var result = Mapper<OcrResults>.MapFromJson(await response.Content.ReadAsStringAsync());
return result;
}
UPDATE 3: I tried this code, but it failed with a Bad Request on iOS. I'm using the ExtractTextFromImageUrlAsync. I did get a "file too large" error using the ExtractTextFromImageStreamAsync, so that method appears to have worked.
https://github.com/HoussemDellai/Microsoft-Cognitive-Services-API/blob/master/ComputerVisionApplication/ComputerVisionApplication/Services/ComputerVisionService.cs
UPDATE 4: I removed Microsoft.Net.Http 2.9 from all the Projects and commented out System.Net.Http from all the app.config files. Both methods now work in the Android and UWP app. I still can't get the iOS app to work. The Project Oxford Nuget fails at this line requestObject.url = imageUrl; (see GitHub). The Rest method fails with a Bad Request, but I managed to catch a "InvalidImageUrl" message, so something is happening when the imageUrl is encoded. At this stage, I believe this is a Xamarin issue that's specific to iOS 10.4.0.
I'm trying to get a response from a HTTP request but i seem to be unable to. I have tried the following:
public Form1() {
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("someUrl");
string content = "someJsonString";
HttpRequestMessage sendRequest = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);
sendRequest.Content = new StringContent(content,
Encoding.UTF8,
"application/json");
Send message with:
...
client.SendAsync(sendRequest).ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
});
} // end public Form1()
With this code, i get back the status code and some header info, but i do not get back the response itself. I have tried also:
HttpResponseMessage response = await client.SendAsync(sendRequest);
but I'm then told to create a async method like the following to make it work
private async Task<string> send(HttpClient client, HttpRequestMessage msg)
{
HttpResponseMessage response = await client.SendAsync(msg);
string rep = await response.Content.ReadAsStringAsync();
}
Is this the preferred way to send a 'HttpRequest', obtain and print the response? I'm unsure what method is the right one.
here is a way to use HttpClient, and this should read the response of the request, in case the request return status 200, (the request is not BadRequest or NotAuthorized)
string url = 'your url here';
// usually you create on HttpClient per Application (it is the best practice)
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).GetAwaiter().GetResult())
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().GetAwaiter().GetResult();
}
}
and for full details and to see how to use async/await with HttpClient you could read the details of this answer
How to consume RestApi using c# and to store the content of responses in json file? i.e When I run the program, it should call API and automatically it should store the json content in json file.
How can it be possible using Asp.Net?
You should use HTTP POST
using System.Net.Https; // Add this library
using (var client = new HttpClient())
{
var values = "DataToSend";
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://sit.com/sample.aspx", content);
var responseString = await response.Content.ReadAsStringAsync(); //JSON
}
You can call any rest api using httpclient(Microsoft.AspNet.WebApi.Client)
Following method returns a json string async which you can save later
static async Taskstring> GetContentAsync(string path)
{
using (var httpClient = new HttpClient())
return await httpClient.GetStringAsync(address);
}
to get json content synchronously
using (var client = new HttpClient())
{
var response = client.GetAsync("http://example.com").Result;
if (response.IsSuccessStatusCode)
{
string responseString = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseString);//you can save the responseString here
}
}
or use open source library like RestSharp
var client = new RestClient("http://example.com");
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
More examples can be found https://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client or using restsharp