uri is too long when I try to send a base64 using xamarin forms - http

I am working with xamarin.forms and System.Net.Http;
I am sending a photo using a post function which is this:
public static async Task<String> PostImagemAsync(User user)
{
using (var client = new HttpClient())
{
try
{
var values = new List<KeyValuePair<string, string>>(0);
values.Add(new KeyValuePair<string, string>("email", user.usua_login));
values.Add(new KeyValuePair<string, string>("senha", user.usua_senha));
values.Add(new KeyValuePair<string, string>("foto", user.cont_imagem));
values.Add(new KeyValuePair<string, string>("json", "1"));
var content = new FormUrlEncodedContent(values);
HttpResponseMessage response = await client.PostAsync("http://ws.neosuite.com.br/login.asmx/foto", content);
var json = response.Content.ReadAsStringAsync().Result;
json = json.Substring(json.IndexOf('['));
json = json.Substring(0, json.LastIndexOf(']') + 1);
var userImage = JsonConvert.DeserializeObject<List<User>>(json);
return userImage[0].cont_imagem;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
}
My image (foto) is a base64 And it does I get this error when I try to send it:
Invalid URI: The Uri string is too long.
How to solve that?

Without adding your POST content into url, add that to body using following code
var uri = new Uri (string.Format ("http://ws.neosuite.com.br/login.asmx/foto", string.Empty));
var json = JsonConvert.SerializeObject (user);//user object or you can create your own jason here
var content = new StringContent (json, Encoding.UTF8, "application/json");
var response = await client.PostAsync (uri, content);

Related

Call simple POST API from console App in VS2019 with XML

I have referred the Trying to call simple POST API from console App in VS2019. But, need to pass XML method in post instead of JSON . Any suggestions ?
static async Task Main(string[] args)
{
var TicketTask = await createTicket();
}
async static Task<string> createTicket()
{
var content = "unknown error";
using (var httpClient = new System.Net.Http.HttpClient())
{
using (var request = new System.Net.Http.HttpRequestMessage(new HttpMethod("POST"), "http://1.0.01.1/slive/"))
{
try
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("username:password"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("<soapenv:Envelope xmlns:xsi...", Encoding.UTF8, "application/xml"); ????? need to post a xml method here
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml");
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
Console.WriteLine(response);
}
catch (Exception ex)
{
content = ex.Message;
}
}
}
return content;
Found the solution, please correct me if there is a better way:
async static Task<string> createTicket2()
{
var content = "unknown error";
using (var httpClient = new System.Net.Http.HttpClient())
{
using (var request = new System.Net.Http.HttpRequestMessage(new HttpMethod("POST"), "http://10/sap-lve/"))
{
try
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("an:s"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
String str1 = #"<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><Get_api_version xmlns='http://e.s.a.com'/></s:Body></s:Envelope>";
**request.Content = new StringContent(str1, Encoding.UTF8, "text/xml");** ;
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml");
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false);
content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
//Console.WriteLine(response);
var result = response.Content.ReadAsStringAsync();
Console.WriteLine(result.Result);
}
catch (Exception ex)
{
content = ex.Message;
}
}
}
return content;
}

Search code in azure devops projects with REST api

i am trying to search code through some project, i didnt succeed to recieve a proper response.
that what i did:
public async void GetProjects()
{
try
{
var personalaccesstoken = "mypersonalPat";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
var httpClient = new HttpClient();
var list = new List<KeyValuePair<string, string>>();
list.Add(new KeyValuePair<string, string>("searchText", "a"));
list.Add(new KeyValuePair<string, string>("$top", "10"));
var content = new FormUrlEncodedContent(list);
var response = await httpClient.PostAsync("https://almsearch.dev.azure.com/myorganization/myproject/_apis/search/codesearchresults?api-version=5.1-preview.1", content);
var res = await response.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
in the response i got 203 status message, in the res i got this (formatted as XML):
Azure DevOps Services | Sign In var __vssPageContext = {"webContext":{"user":{"id":"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa","name":"Anonymous","email":"","uniqueName":"TEAM FOUNDATION\\Anonymous"},"host":{"id":"7d0cc8e9-39e8-4313-9ff3-23ace0f8f4cf","name":"TEAM FOUNDATION","uri":"https://spsprodweu4.vssps.visualstudio.com/","relativeUri":"/","hostType":"deployment","scheme":"https","authority":"spsprodweu4.vssps.visualstudio.com"}},"moduleLoaderConfig":{"baseUrl":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/","paths":{"Profile/Scripts/Resources":"en-US","VSS/Resources":"en-US","Account/Scripts/Resources":"en-US","UserManagement/Scripts/Resources":"en-US","Authentication/Scripts/Resources":"en-US"},"map":{},"contributionPaths":{"VSS":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/VSS","pathType":"default"},"VSS/Resources":{"value":"en-US","pathType":"resource"},"q":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/q","pathType":"default"},"knockout":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/knockout","pathType":"default"},"mousetrap":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/mousetrap","pathType":"default"},"mustache":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/mustache","pathType":"default"},"react":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/react.15.3","pathType":"default"},"react-dom":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/react-dom.15.3","pathType":"default"},"react-transition-group":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/react-transition-group.15.3","pathType":"default"},"jQueryUI":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/jQueryUI","pathType":"default"},"jquery":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/jquery","pathType":"default"},"OfficeFabric":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/OfficeFabric","pathType":"default"},"tslib":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/tslib","pathType":"default"},"#uifabric":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/#uifabric","pathType":"default"},"VSSUI":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/VSSUI","pathType":"default"}},"shim":{"jquery":{"deps":[],"exports":"jQuery"}},"waitSeconds":30},"coreReferences":{"stylesheets":[{"url":"/_static/tfs/M166_20200303.4/_cssbundles/Default/vss-bundle-ext-core-css-vgEHbWqZ4eb0vmOdl2cWjkpPtqcsX1GJCq4DnY78oN3s=","highContrastUrl":null,"isCoreStylesheet":true}],"scripts":[{"identifier":"JQuery","url":"/_static/3rdParty/_scripts/jquery-2.2.4.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"JQueryXDomain","url":"/_static/3rdParty/_scripts/jquery.xdomainrequest.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"Promise","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/promise.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"GlobalScripts","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/global-scripts.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"LoaderFixes","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/pre-loader-shim.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":false},{"identifier":"AMDLoader","url":"/_static/3rdParty/_scripts/require.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"LoaderFixes","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/post-loader-shim.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":false}],"coreScriptsBundle":{"identifier":"CoreBundle","url":"/_public/_Bundling/Content?bundle=vss-bundle-basejs-v9GpWWBnsWqhM23ijhK2HfAqLowTXGUqZLDRsBCZbkfY=","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},"extensionCoreReferences":{"identifier":"CoreBundle","url":"/_public/_Bundling/Content?bundle=vss-bundle-ext-core-vjMBLvR7Lq0Z_oS-OpRMsP9FOHhkdmDXf0mCbsK5c0RI=","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true}},"webAccessConfiguration":{"isHosted":true,"paths":{"rootPath":"/","staticContentRootPath":"/","staticContentVersion":"M166_20200303.4","resourcesPath":"/_static/tfs/M166_20200303.4/_content/","staticRootTfs":"/_static/tfs/M166_20200303.4/","cdnFallbackStaticRootTfs":"/_static/tfs/M166_20200303.4/","staticRoot3rdParty":"/_static/3rdParty/"},"api":{"webApiVersion":"1","areaPrefix":"_","controllerPrefix":""},"mailSettings":{"enabled":false},"registryItems":{}},"microsoftAjaxConfig":{"cultureInfo":{"name":"en-US","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":true,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"$","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":1,"PercentNegativePattern":1,"NegativeInfinitySymbol":"-∞","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"∞","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"‰","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"0001-01-01T00:00:00","MaxSupportedDateTime":"9999-12-31T23:59:59.9999999","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":true},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, MMMM d, yyyy h:mm:ss tt","LongDatePattern":"dddd, MMMM d, yyyy","LongTimePattern":"h:mm:ss tt","MonthDayPattern":"MMMM d","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH':'mm':'ss 'GMT'","ShortDatePattern":"M/d/yyyy","ShortTimePattern":"h:mm tt","SortableDateTimePattern":"yyyy'-'MM'-'dd'T'HH':'mm':'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy'-'MM'-'dd HH':'mm':'ss'Z'","YearMonthPattern":"MMMM yyyy","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":true,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]},"numberShortForm":{"QuantitySymbols":["K","M","B"],"NumberGroupSize":1000,"ThousandSymbol":"K"},"eras":null}},"timeZonesConfiguration":{},"featureAvailability":{"featureStates":{"VisualStudio.Services.Contribution.EnableOnPremUnsecureBrowsers":false,"VisualStudio.Service.WebPlatform.ClientErrorReporting":false,"Microsoft.VisualStudio.Services.Gallery.Client.UseCdnAssetUri":false,"VisualStudio.Services.WebAccess.SubresourceIntegrity":false,"VisualStudio.Services.IdentityPicker.ReactProfileCard":true}},"appInsightsConfiguration":{"enabled":false,"instrumentationKey":"00000000-0000-0000-0000-000000000000","insightsScriptUrl":null},"diagnostics":{"sessionId":"24ec3e5b-2a51-44d0-8738-32e2f2c48c12","activityId":"24ec3e5b-2a51-44d0-8738-32e2f2c48c12","bundlingEnabled":true,"webPlatformVersion":"M166","serviceVersion":"Dev18.M166.1 (build: AzureDevOps_M166_20200320.5)"},"navigation":{"topMostLevel":"deployment","area":"","currentController":"Signin","currentAction":"Index","routeId":"LegacyWebAccessRoute","routeValues":{"controller":"Signin","action":"Index"}},"globalization":{"explicitTheme":"","theme":"Default","culture":"en-US","timezoneOffset":0,"timeZoneId":"UTC"},"serviceInstanceId":"951917ac-a960-4999-8464-e3f0aa25b381","hubsContext":{},"serviceLocations":{"locations":{"951917ac-a960-4999-8464-e3f0aa25b381":{"Application":"https://spsprodweu4.vssps.visualstudio.com/","Deployment":"https://spsprodweu4.vssps.visualstudio.com/"}}}}; var __cultureInfo = __vssPageContext.microsoftAjaxConfig.cultureInfo;
hope someone can tell me the proper way to send the post request.
Try with below script:
try
{
var personalaccesstoken = "{token}";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
var httpClient = new HttpClient();
var newcontent = new StringContent("{\"searchText\":\"gradle\",\"$top\":33}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = await client.PostAsync("https://almsearch.dev.azure.com/{org}/{project}/_apis/search/codesearchresults?api-version=5.1-preview.1", newcontent))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Result:

Asp.net Web Api Authentication and password encryption

I have a autentication with the web api working, but is using the email and password to autenticate, how can i change so that web api uses a username field and password for the autentication?
Another thing, how can i change the encrytion method for the password?
The Autentication is made this away:
public async Task<string> LoginAsync(string username, string password)
{
try
{
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password")
};
Settings.Serverdown = false;
var request = new HttpRequestMessage(HttpMethod.Post, "http://192.168.44.22:56479/Token");
request.Content = new FormUrlEncodedContent(keyValues);
var client = new HttpClient();
client.Timeout = TimeSpan.FromMilliseconds(6000);
var response = await client.SendAsync(request);
var jwt = await response.Content.ReadAsStringAsync();
Settings.LoginSucess = response.IsSuccessStatusCode;
Settings.Username = username;
JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(jwt);
var accessToken = jwtDynamic.Value<string>("access_token");
Settings.AccessToken = accessToken;
}
catch (Exception e)
{
XFToast.LongMessage("Cant reach the server");
Settings.Serverdown = true;
}
var accessToken2=Settings.AccessToken;
return accessToken2;
}
Thanks

Parameter has all propertys after webrequest

I have a really simple ASP.NET Api Controller with one method.
public HttpResponseMessage<User> Post(User user)
{
return new HttpResponseMessage<User>(new User() { Name = "New User at Server" });
}
My debugger says that the method is called but the problem is that the parameter "user" has all its content set to null; I am using Fiddler to look at request and response.. and all looks good.
This is my service code in the client.
public void AddUser(Models.User user, Action<Models.User> ShowResult)
{
var uiThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext();
string url = "http://localhost:4921/User";
Uri uri = new Uri(url, UriKind.Absolute);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var sendWebPost = Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null)
.ContinueWith(task =>
{
Tuple<string, string>[] stringToSend = { Tuple.Create<string, string>("user", ObjectToJson<Models.User>(user)) };
var bytesToSend = GetRequestBytes(stringToSend);
using (var stream = task.Result)
stream.Write(bytesToSend, 0, bytesToSend.Length);
}
).ContinueWith(task =>
{
Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null)
.ContinueWith<WebResponse>(task2 => { ValidateResponse(task2); return task2.Result; })
.ContinueWith<Models.User>(task3 => {return JsonToObject<Models.User>(task3);})
.ContinueWith(task4 => { TryClearWorking(); ShowResult(task4.Result); }, uiThreadScheduler);
});;
}
public static string ObjectToJson<T>(T obj) where T : class
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
MemoryStream stream = new MemoryStream();
StreamReader sr = new StreamReader(stream);
serializer.WriteObject(stream, obj);
sr.BaseStream.Position = 0;
string jsonString = sr.ReadToEnd();
return jsonString;
}
protected static byte[] GetRequestBytes(Tuple<string, string>[] postParameters)
{
if (postParameters == null || postParameters.Length == 0)
return new byte[0];
var sb = new StringBuilder();
foreach (var key in postParameters)
sb.Append(key.Item1 + "=" + key.Item2 + "&");
sb.Length = sb.Length - 1;
return Encoding.UTF8.GetBytes(sb.ToString());
}
Anyone who can give me some ideas where to start to look for errors.....
You need to set the Content-Length header.

ASP .Net Web API downloading images as binary

I want to try to use Web API make a rest call but I want the response to be the actual binary image stored in a database, not a JSON base64 encoded string. Anyone got some pointers on this?
Update-
This is what I ended up implementing:
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(new MemoryStream(profile.Avatar));
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "avatar.png";
return result;
You can set the response content to a StreamContent object:
var fileStream = new FileStream(path, FileMode.Open);
var resp = new HttpResponseMessage()
{
Content = new StreamContent(fileStream)
};
// Find the MIME type
string mimeType = _extensions[Path.GetExtension(path)];
resp.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType);
While this has been marked as answered, it wasn't quite what I wanted, so I kept looking. Now that I've figured it out, here's what I've got:
public FileContentResult GetFile(string id)
{
byte[] fileContents;
using (MemoryStream memoryStream = new MemoryStream())
{
using (Bitmap image = new Bitmap(WebRequest.Create(myURL).GetResponse().GetResponseStream()))
image.Save(memoryStream, ImageFormat.Jpeg);
fileContents = memoryStream.ToArray();
}
return new FileContentResult(fileContents, "image/jpg");
}
Granted, that's for getting an image through a URL. If you just want to grab an image off the file server, I'd imagine you replace this line:
using (Bitmap image = new Bitmap(WebRequest.Create(myURL).GetResponse().GetResponseStream()))
With this:
using (Bitmap image = new Bitmap(myFilePath))
EDIT: Never mind, this is for regular MVC. for Web API, I have this:
public HttpResponseMessage Get(string id)
{
string fileName = string.Format("{0}.jpg", id);
if (!FileProvider.Exists(fileName))
throw new HttpResponseException(HttpStatusCode.NotFound);
FileStream fileStream = FileProvider.Open(fileName);
HttpResponseMessage response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
response.Content.Headers.ContentLength = FileProvider.GetLength(fileName);
return response;
}
Which is quite similar to what OP has.
I did this exact thing. Here is my code:
if (!String.IsNullOrWhiteSpace(imageName))
{
var savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine(uploadPath, imageName));
var image = System.Drawing.Image.FromFile(savedFileName);
if (ImageFormat.Jpeg.Equals(image.RawFormat))
{
// JPEG
using(var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Jpeg);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
else if (ImageFormat.Png.Equals(image.RawFormat))
{
// PNG
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Png);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
else if (ImageFormat.Gif.Equals(image.RawFormat))
{
// GIF
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Gif);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/gif");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
}
And then on the client:
var client = new HttpClient();
var imageName = product.ImageUrl.Replace("~/Uploads/", "");
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
Properties.Settings.Default.DeviceMediaPath + "\\" + imageName);
var response =
client.GetAsync(apiUrl + "/Image?apiLoginId=" + apiLoginId + "&authorizationToken=" + authToken +
"&imageName=" + product.ImageUrl.Replace("~/Uploads/","")).Result;
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsByteArrayAsync().Result;
using (var ms = new MemoryStream(data))
{
using (var fs = File.Create(path))
{
ms.CopyTo(fs);
}
}
result = true;
}
else
{
result = false;
break;
}
This task is much easily achieved without using WebAPI. I would implement a custom HTTP handler for a unique extension, and return the binary response there. The plus is that you can also modify the HTTP Response headers and content type, so you have absolute control over what is returned.
You can devise a URL pattern (defining how you know what image to return based on its URL), and keep those URLs in your API resources. Once the URL is returned in the API response, it can be directly requested by the browser, and will reach your HTTP handler, returning the correct image.
Images are static content and have their own role in HTTP and HTML - no need to mix them with the JSON that is used when working with an API.

Resources