Sending image as base64string to WebAPI; base64 string is too long - c#

I recently followed these tutorials by Ahsan Siddique
Developing RESTful API in ASP.Net With Azure Database.
Part 1
https://www.c-sharpcorner.com/article/creating-sql-database-in-azure-portal/
part 2
https://www.c-sharpcorner.com/article/developing-restful-api-in-asp-net-with-add-method/
Part 3
https://www.c-sharpcorner.com/article/developing-restful-apis-in-asp-net-with-retrieve-update-and-delete-functions/
Consuming RESTful API in Xamarin.Android
part 4
https://www.c-sharpcorner.com/article/consuming-restful-apis-in-xamarin-android/
I managed to get all the codes to work but I got stuck at the part where i'm trying to pass the base64 string to the web api. The tutorial didn't have the portion that I got stuck at. I tested my POST API on Postman and I get this error message, "HTTP Error 414. The request URL is too long."
Below you can see a portion of my codes:
public String BitmapToBase64(Bitmap bitmap)
{
//Java.IO.ByteArrayOutputStream byteArrayOutputStream = new Java.IO.ByteArrayOutputStream();
MemoryStream memStream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, memStream);
byte[] byteArray = memStream.ToArray();
return Base64.EncodeToString(byteArray, Base64Flags.Default);
}
User user = new User ();
user.ID = "1";
user.name = "Kelly";
user.profilepic = BitmapToBase64(NGetBitmap(uri)); //this is the part where base64string is too long
HttpClient client = new HttpClient();
string url = $"http://test.azurewebsites.net/api/User/{user.ID}?name={user.name}&profilepic={user.profilepic}";
var uri1 = new System.Uri(url); //base64
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
var json = JsonConvert.SerializeObject(feedback);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await client.PostAsync(uri1, content);
if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
{
Toast.MakeText(this, "Your profile is updated.", ToastLength.Long).Show();
}
else
{
Toast.MakeText(this, "Your profile is not updated." + feedback.profilepic, ToastLength.Long).Show();
}
I need help! Thank you in advance!
Update:
This is how my controller class currently look like
public HttpResponseMessage Update_User(int ID, string name, string profilepic)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
UserTable newUser = new UserTable();
var entry = db.Entry<UserTable>(newUser);
entry.Entity.ID = ID;
entry.Entity.name = name;
entry.Entity.profilepic = profilepic;
entry.State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.Accepted, "Your profile is updated.");
}

As mentioned in the comments, don't send the base64 image as part of the url/GET param.
Instead attach it to the body of the POST request.
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("profilepic", user.profilepic)
});
var result = await client.PostAsync(url, content);

Related

Strange response from Asp.Net Web Api Post

I have a Asp.Net Web Api like the following
public async Task<IHttpActionResult> Post(Guid id, OrganisationModel model)
{
try
{
_orgService.AddNewOrganisationToParent(newOrg, org);
await Context.SaveChangesAsync();
return Ok(newOrg.Id);
}
catch (Exception ex)
{
Log.ErrorFormat("Problem creating new organisation {0}. Error {1}", UserId, ex);
return InternalServerError(ex);
}
}
When I call this from another Asp.Net Web application with the following;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var newOrg = Newtonsoft.Json.JsonConvert.SerializeObject(new
{
name = systemTree.Name,
type = 0
});
var content = new StringContent(newOrg.ToString(), Encoding.UTF8, "application/json");
var newOrgId = Guid.Empty;
using (var response = await client.PostAsJsonAsync(orgEndpoint + orgId, content))
{
response.EnsureSuccessStatusCode();
newOrgId = response.Content.ReadAsAsync<Guid>().Result;
}
The response is rather strange, the code shown throws and exception "exceptionMessage": "Unable to translate bytes [B4] at index 3 from specified code page to Unicode.",
If I read this as a string I get the following
"SJN4OMN4��MIK2�M574Ե0H6�500H1NL2J�4IR\u0002\0"
Is there something I am missing? Thanks in advance.

Issue in http client authentication header and posting multipart form data

I am developing a windows phone 8 app. Now i have to post an image selected from my gallery to the web api. This api is password protected and therefore username and password in authentication header of http client library need to be passed on. Secondly data in the form of image, aboutme, and other properties are to be posted at api. But there is an issue i dont know some how its crashing . I have given text api in this code snippet if actual needed then u can ask me. But need to know wat i am doing wrong in passing http client header with form data.
My code snippet is below given:
async void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
// MessageBox.Show(e.ChosenPhoto.Length.ToString());
//Code to display the photo on the page in an image control named myImage.
photoStream = new MemoryStream();
e.ChosenPhoto.CopyTo(photoStream);
fileName = e.OriginalFileName;
MessageBox.Show(fileName);
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
int a = bmp.PixelHeight;
int b = bmp.PixelWidth;
ApplicationSettingHelper.AddOrUpdateValue("profilepicture", e.OriginalFileName);
ApplicationSettingHelper.Save();
string User_id = "221296";
string About_me = AboutMeText.Text;
string Country = "Dubai";
string Session_token = "54143870560e6136764dc9.77573702";
byte[] Imagedata = bitmapConverter(bmp);
UploadFile(User_id, About_me, Country, Session_token, photoStream);
}
////////////////////////////////////////////////////////
private async void UploadFile(string user_id,string about_me,string country,string session_token,MemoryStream photoStream)
{
try
{
// Make sure there is a picture selected
if (photoStream != null)
{
const string uri = "http://api.etc";
using (var client = new HttpClient())
{
var byteArray = Encoding.UTF8.GetBytes("prototype:prototype");
var header = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(byteArray));
client.DefaultRequestHeaders.Authorization = header;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(photoStream), "profile_image");
content.Add(new StringContent(user_id), "user_id");
content.Add(new StringContent(about_me), "about_me");
content.Add(new StringContent(country), "country");
content.Add(new StringContent(session_token), "session_token");
// var result = await client.PostAsync(uri, content);
await client.PostAsync(uri, content)
.ContinueWith((postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
}
}
catch(Exception ex)
{
var message = ex.Message + ex.StackTrace.ToString();
var test = message;
}
}

How to sent data with restfull web service in C#

I m developing a Windows Phone 8.1 Application.
I'm newbie in C# and WP. I used restfull web services for sql server connection but i can't send data to server. I had an error message as "Bad Request".
This is my login page code bihend
KullaniciManager km = new KullaniciManager();
km.Login();
HttpClient httpClient = new System.Net.Http.HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:3577/KullaniciService.svc/Login");
HttpResponseMessage response = await httpClient.SendAsync(request);
MessageDialog msgbox = new MessageDialog("Serverdan gelecek hata mesajı");
await msgbox.ShowAsync();
My BLL code is here.
public LoginResponse KullaniciKontrolEt(string kulAdi, string sifre)
{
LoginResponse response = null;
using (NeydiolilacEntities noi = new NeydiolilacEntities())
{
object data = noi.ta_Kullanici.Where(x => x.Kul_Ad == kulAdi && x.Kul_Sifre == sifre && x.Kul_Statu == true).SingleOrDefault();
response = new LoginResponse()
{
Data = data
};
return response;
}
Thanks for your help :)
*
Hi Asim,
This will help you I hope
Note : Code for Win8.1
public async Task<string> GeneralRequestHandler(string RequestUrl, object ReqObj)
{
try
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(ReqObj);
HttpContent content = new StringContent(json);
Windows.Web.Http.IHttpContent c = new Windows.Web.Http.HttpStringContent(json);
c.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/json");
Windows.Web.Http.Filters.HttpBaseProtocolFilter aHBPF = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
aHBPF.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);
aHBPF.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.InvalidName);
string responseText;
using (var handler = new Windows.Web.Http.HttpClient(aHBPF))
{
Windows.Web.Http.HttpResponseMessage r = await handler.PostAsync(new Uri(RequestUrl), c);
responseText = await r.Content.ReadAsStringAsync();
}
}
catch (HttpRequestException ex)
{
}
return responseText;
}
*

How to send MultipartForm using POST method in (Windows Phone 8.1) C#

Can any one explain how can i make POST request to a URL on web with different type of data, in my case i have an image and two string type values to send to a server in PHP.
here what i already have done
var stream = await file.OpenStreamForReadAsync();
var streamcontent = new StreamContent(stream);
streamcontent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "photo",
FileName = file.Name
};
streamcontent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
MultipartFormDataContent multipart = new MultipartFormDataContent();
multipart.Add(streamcontent);
try
{
descContent = mytextbox.Text;
var stringcontent = new StringContent(descContent);
stringcontent.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("description", descContent));
multipart.Add(stringcontent);
HttpResponseMessage res = await client.PostAsync(new Uri("http://localhost/web/test/index.php"), multipart);
res.EnsureSuccessStatusCode();
mytextbox.Text = await res.Content.ReadAsStringAsync();
}
catch (HttpRequestException ex)
{
mytextbox.Text = ex.Message;
}
this code will send the image file but not the description(string), i have searched over the internet but I could not find appropriate answer.
here is the PHP code
if (isset($_FILES['photo']))
{
echo $_FILES["photo"]["name"] . "<br>";
}
else
{
echo "Image: Error<br>";
}
if (isset($_POST['description']))
{
echo $_POST['description'];
}
else
{
echo "Text: Error";
}
any response will be highly appreciated.
thank you
I have search a lot and finally got the way out. here is the code
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://www.yourdomain.com");
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new StringContent("your string type data you want to post");
form.Add(content, "name");
var stream = await file.OpenStreamForReadAsync();
content = new StreamContent(stream);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "image",
FileName = file.Name
};
form.Add(content);
var response = await client.PostAsync("index.php", form);
mytextblock.Text = response.Content.ReadAsStringAsync();
I wrote it on my blog here is the code. :-)
HappyCoding
Upload files with HTTPWebrequest (multipart/form-data)
http://www.paraesthesia.com/archive/2009/12/16/posting-multipartform-data-using-.net-webrequest.aspx/

Upload files to Google Drive in Windows Store App

UPDATE 1
I think I am using incorrect URL, this doc says to use "https://www.googleapis.com/drive/v2/files" & this doc says to use "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart". Though I am getting same 400 bad request.
Can I use Google Drive upload REST API in background uploader class?
I am following this doc from Google Drive to upload files but I am getting 400 - Bad request. What's wrong with my code?
public static async Task UploadFileAsync(Token AuthToken, StorageFile file, DriveFile objFolder)
{
try
{
if (!httpClient.DefaultRequestHeaders.Contains("Authorization"))
{
httpClient.DefaultRequestHeaders.Add("Authorization", AuthToken.TokenType + " " + AuthToken.AccessToken);
}
var JsonMessage = JsonConvert.SerializeObject(objFolder);
/*JsonMessage = {"title":"c4611_sample_explain.pdf","mimeType":"application/pdf","parents":[{"id":"root","kind":"drive#fileLink"}]}*/
var JsonReqMsg = new StringContent(JsonMessage, Encoding.UTF8, "application/json");
var fileBytes = await file.ToBytesAsync();
var form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(fileBytes));
form.Add(JsonReqMsg);
form.Headers.ContentType = new MediaTypeHeaderValue("multipart/related");
var UploadReq = await httpClient.PostAsync(new Uri("https://www.googleapis.com/drive/v2/files?uploadType=multipart"), form);
if (UploadReq.IsSuccessStatusCode)
{
var UploadRes = await UploadReq.Content.ReadAsStringAsync();
}
else
{
}
}
catch (Exception ex)
{
}
}
You must use https://www.googleapis.com/upload/drive/v2/files
I have a working sample here (sorry, the JSON string is hard coded):
// Multipart file upload
HttpClient client = new HttpClient();
string uriString = "https://www.googleapis.com/upload/drive/v2/files?key=<your-key>&access_token=<access-token>&uploadType=multipart";
Uri uri = new Uri(uriString);
HttpContent metadataPart = new StringContent(
"{ \"title\" : \"My File\"}",
Encoding.UTF8,
"application/json");
HttpContent mediaPart = new StringContent(
"The naughty bunny ate all the cookies.",
Encoding.UTF8,
"text/plain");
MultipartContent multipartContent = new MultipartContent();
multipartContent.Add(metadataPart);
multipartContent.Add(mediaPart);
HttpResponseMessage response = await client.PostAsync(uri, multipartContent);
string responseString = await response.Content.ReadAsStringAsync();

Categories

Resources