Get image by client request in Blazor - asp.net-core

I try to get a Base64 from a image-URL in my hosted Blazor Webassambly. The URL contains a link to a picture.
using (var client = new HttpClient())
{
var bytes = await client.GetByteArrayAsync(url); // there are other methods if you want to get involved with stream processing etc
var base64String = Convert.ToBase64String(bytes);
return base64String;
}
Throws Exception:
TypeError: Failed to fetch
The Exception is thrown with any client method.
var result = await client.[X](url);
Why its impossible to make a request with he http client?

I would try it with first retrieving the link to the picture and then downloading the bytes from there.
string pictureLink = await client.GetStringAsync(url);
var base64String = Convert.ToBase64String(await client.GetByteArrayAsync(pictureLink));

Related

How to get microsoft account profile photo after login with application in mvc

With the help of claimprincipal, I'm able to get the details of signedin user as below but its not giving any pic related information as google does:
https://apis.live.net/v5.0/{USER_ID}/picture?type=large
which says The URL contains the path '{user_id}', which isn't supported.
Even tried
https://graph.microsoft.com/v1.0/me/photo/$value
which is asking for access token, but I am not sure what have to be passed
string userName = ClaimsPrincipal.Current.FindFirst("name").Value;
string userEmail = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
Wanted an image which was added in any outlook account
For Image to show.. We have to use beared token and have to convert the image into memory stream and then have to used it.. I have done it in below ways. Hope this help ...
var client = new RestClient("https://login.microsoftonline.com/common/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"code={code}&client_id={OutClientId}&client_secret={SecretKey}&redirect_uri={OutRedirectUrl}&grant_type=authorization_code", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Token jsonContent = JsonConvert.DeserializeObject<Token>(response.Content);
var Token = jsonContent.AccessToken;
var TokenType = jsonContent.TokenType;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
HttpResponseMessage response1 = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photos/96x96/$value");
if (response1.StatusCode == HttpStatusCode.OK)
{
using (Stream responseStream = await response1.Content.ReadAsStreamAsync())
{
MemoryStream ms = new MemoryStream();
responseStream.CopyTo(ms);
byte[] buffer = ms.ToArray();
string result = Convert.ToBase64String(buffer);
HttpContext.Session[AppConstants.UserImage] = String.Format("data:image/gif;base64,{0}", result);
responseStream.Close();
}
}
Is there any reason you are using the live.net apis? Instead of the Microsoft Graph APIs? Microsoft Graph APIs are the future for all user data within Microsoft 365 consumer and commercial accounts.
You can get the Users photo very easily as described here https://learn.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-1.0
GET /me/photo/$value
As you are using ASP.NET MVC, there is an SDK you can use that makes this very easy too.
https://learn.microsoft.com/en-us/graph/sdks/sdks-overview?context=graph%2Fapi%2F1.0&view=graph-rest-1.0

WCF responds with HTTP 400 to serialized JSON string from Razor Pages app

I'm trying to POST a request containing JSON from a Razor Pages app to a WCF service endpoint expecting a Json WebMessageFormat and Bare BodyStyle.The JSON passes just fine via Postman, but not when I send it through http-client. Wireshark also shows some extra bytes around JSON in the http-client produced packet that are not present in the Postman packet. Wireshark also reports this as line-based text data: application/json for the Postman packet. The .Net packet is JavaScript Object Notation: application/json.
Here's my C# code to send the JSON to the WCF endpoint:
var client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8000");
dynamic foo = new ExpandoObject();
foo.position = 1;
var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(foo), System.Text.Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:8000/WCFService/ControllerV1/PostJSON");
request.Headers.Add("cache-control", "no-cache");
request.Headers.Add("Accept", "*/*");
request.Headers.Add("Connection", "keep-alive");
request.Content = content;
try
{
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException e)
{
Console.WriteLine(e.Message);
}
And here's my WCF endpoint declaration:
[OperationContract, WebInvoke(Method="POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
void PostJSON(string jsonString);
I would expect the packets to produce the same response from the server, but, what appears to be the same string produces a response 200 when the packet is built by postman and a response 400 when built by .Net. I'm clearly missing something subtle here, but I can't seem to tease it out.
There are 2 possible BodyStyle for request and response, wrapped or bare. When you specify wrapped body style the WCF service expects a valid json to be passed which in your case would be
//note that property name is case sensitive and must match service parameter name
{
"jsonString": "some value"
}
And when you specify bare format the service expects only plain string value (in case of primitive type as yours) as the request like this
"some value"
When you serialize your object like this
dynamic foo = new ExpandoObject();
foo.position = 1;
string result = JsonConvert.SerializeObject(foo);
the result contains the following json
{
"position":1
}
which corresponds to wrapped format and the service returns 400: Bad Request. All you need to do is to turn this json into valid json string value like this
"{\"position\":1}"
It can be done by repeated JsonConvert.SerializeObject call
dynamic foo = new ExpandoObject();
foo.position = 1;
string wrapped = JsonConvert.SerializeObject(foo);
string bare = JsonConvert.SerializeObject(wrapped);
var content = new StringContent(bare, System.Text.Encoding.UTF8, "application/json");

Get string returned from a PostAsync event

I'm using HttpClient like this in my console app:
using (var http = new HttpClient(handler))
{
http.BaseAddress = new Uri("http://127.0.0.1:34323/");
var response = await http.PostAsync("/api/generate", new StringContent(
JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"));
Console.WriteLine(response.Content.ToString());
}
In debug mode, I can see that the controller is returning a string of JSON.
However, I only get this written to the console:
System.Net.Http.StreamContent
How can I get it to write the actual JSON that's being returned?
Thanks!
Try below line:
Console.WriteLine(response.Content.ReadAsStringAsync().Result.ToString());

OneDrive REST API Download file

I'm using the REST API of OneDrive in my WCF Web Service. Everything works well but the Download of a file. I need to get the Stream object of the file downloaded but MemoryStream class gives me an Exception about ReadTimeout and WriteTimeout.
This is the code:
.... some code ....
var rClient = new RestClient("https://apis.live.net/v5.0/");
var rRequest = new RestRequest(rootFile.id + "/content", Method.GET);
rRequest.AddParameter("access_token", data.accessToken);
var rResponse = rClient.Execute(rRequest); // THE RESPONSE IS OK
byte[] array = rResponse.RawBytes;
Stream stream = new MemoryStream(array); // PROBLEM HERE!
return stream;
So when I create the Stream Object the MemoryStream throw 2 Exception on the fields ReadTimeout and WriteTimeout saying that they are not supported for this stream.
I don't know how to solve it
As suggested by Will in the comment, I discovered that the Exception on ReadTimeout and WriteTimeout was not the real problem. The Exception was thrown by a null object in the caller method, after the code posted above.
Below there is the point where the Exception was thrown: the Current object was null.
stream = client.DownloadFile(token);
if (stream != null)
{
**WebOperationContext.Current.OutgoingResponse.ContentType = "text/octet-stream";** //HERE
return stream;
}
I removed the line and everything was fixed

How to communicate WCF exceptions to WebClient

I have a WCF web service which throws exceptions when invalid data is submitted. The data is submitted via an HTTP Post using the WebClient object.
Here is the code for the web service:
[WebInvoke(UriTemplate = "update", Method = "POST")]
public JsonValue Update(HttpRequestMessage message)
{
var context = new Entities();
dynamic response = new JsonObject();
// in order to retrieve the submitted data easily, reference the data as a dynamic object
dynamic data = message.Content.ReadAs(typeof(JsonObject), new[] { new FormUrlEncodedMediaTypeFormatter() });
// retrieve the submitted data
int requestId = data.requestId;
int statusId = data.statusId;
string user = data.user;
string encryptedToken = data.token;
string notes = data.notes;
// retrieve the request with a matching Id
var request = context.Requests.Find(requestId);
// make sure the request exists
if (request == null)
throw new FaultException("The supplied requestId does not exist.");
// make sure the submitted encrypted token is valid
var token = DecryptToken(encryptedToken);
if (token == null)
throw new FaultException("Invalid security token.");
// TODO: Validate other token properties (e.g. email)?
if (!request.User.UserName.Equals(token.UserName))
throw new FaultException("Invalid security token.");
// additional logic removed ...
}
And here is the code that submits data to the web service:
// use the WebClient object to submit data to the WCF web service
using (var client = new WebClient())
{
client.Encoding = Encoding.UTF8;
// the data will be submitted in the format of a form submission
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var data = new NameValueCollection();
// prepare the data to be submitted
data.Add("requestId", requestId.ToString());
data.Add("statusId", this.StatusId);
data.Add("token", token.ToString());
data.Add("user", this.User);
data.Add("notes", this.Notes);
// submit the data to the web service
var response = client.UploadValues(this.Address, data);
}
I keep getting an exception with message: "The remote server returned an error: (500) Internal Server Error" at client.UploadValues(this.Address, data);.
Is there a way I can make sure that more detailed information is returned to the WebClient?
Also, how can I make sure that these exceptions (in the WCF service) are logged to the EventLog? (Basically I just need to know what happened).
Take a look at HttpResponseException (namespace Microsoft.ApplicationServer.Http.Dispatcher) - they're the way where you can control the response for error cases. You can specify the status code, and you have control over the HttpResponseMessage, in which you can control the message body.
On the client side, when you call WebClient.UploadValues, wrap that call and catch a WebException. If the service returns a response with a non-successful status code (e.g., 500, 400), the Response property of the WebException will have the body, in which you can read in your client.
Another option is to use HttpClient instead of the WebClient, in which case you can simply look at the HttpResponseMessage directly.