I'm using any one of several examples found all over the place to do a file upload with .net Web API. The files get stored to the server, but the fileData object on the provider always returns empty. Code below.
var url = "api/Documents/fileUpload";
var xhr = new XMLHttpRequest();
var file = document.getElementById("inputFile").files[0];
var formData = new FormData();
formData.append('file', file);
xhr.open("POST", url, true);
xhr.responseType = "text";
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
console.log("photoUpload xhr", xhr);
var responseTypeAsJSON = JSON.parse(xhr.responseText);
currentPhoto.responseText = xhr.responseText;
if (responseTypeAsJSON.result == "SUCCESS") {
currentPhoto.status = "SUCCESSfully uploaded";
}
else {
currentPhoto.status = responseTypeAsJSON.result;
alert(responseTypeAsJSON.message);
}
PhotoClear();
// console.log(currentPhoto);
// console.log("xhr done: ", xhr);
}
}
xhr.send(formData);
// console.log("xhr sent: ", xhr);
CONTROLLER TO RECEIVE:
[HttpPost]
[ActionName("fileUpload")]
public Task<HttpResponseMessage> fileUpload()
{
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
var task = request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(o =>
{
string file1 = provider.FileData.First().LocalFileName.ToString();
// this is the file name on the server where the file was saved
return new HttpResponseMessage()
{
Content = new StringContent("File uploaded.")
};
}
);
return task;
}
Here is the request from Chrome. When I debug the provider, the keys of the form data are empty as well. Yet the file gets put into the AppData
Request URL:http://localhost:4231/api/Documents/fileUpload
Request Headersview source
Content-Type:multipart/form-data; boundary=----WebKitFormBoundarycuGegdEDmBsR0mMl
Origin:http://localhost:4231
Referer:http://localhost:4231/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22
Request Payload
------WebKitFormBoundarycuGegdEDmBsR0mMl
Content-Disposition: form-data; name="testInfo"
some info here for testing
------WebKitFormBoundarycuGegdEDmBsR0mMl
Content-Disposition: form-data; name="file"; filename="irislogo.png"
Content-Type: image/png
------WebKitFormBoundarycuGegdEDmBsR0mMl--
I was running into this exact issue and a small code change fixed the issue.
The line:
var provider = new MultipartFormDataStreamProvider(root);
Should be:
var provider = new MultipartFileStreamProvider(root);
I also had this issue; here is the solution:
public async Task<HttpResponseMessage> Save()
{
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
await Request.Content.ReadAsMultipartAsync(provider);
// provider.FileData will contain your data...
// you can also send form data which will be in provider.FormData
}
Related
I'm writing an API in EF to send FCM notifications:
[HttpPost]
public void PushNotificationToFCM(string deviceTokens, string title, string body, object data, string linkdirection)
{
...
// This registration token comes from the client FCM SDKs.
var registrationToken = deviceTokens;
// See documentation on defining a message payload.
var message = new Message()
{
Apns = new ApnsConfig { Aps = new Aps { ContentAvailable = true, Sound = "default" } },
Data = new Dictionary<string, string>()
{
{ "link", linkdirection },
},
Token = registrationToken,
Notification= new FirebaseAdmin.Messaging.Notification()
{
Title = title,
Body = body,
}
};
// Send a message to the device corresponding to the provided
// registration token.
string response = FirebaseMessaging.DefaultInstance.SendAsync(message).Result;
// Response is a message ID string.
Debug.WriteLine("Successfully sent message: " + response);
}
I tried on Postman or Swagger everything works fine.
I proceed to write the send command in XF:
.xaml.cs
protected async void SendFirebase()
{
string devicetoken = listDeviceID.deviceidphone;
string titlefirebase = "Title";
string bodyfirebase = "Description";
string linkfirebase = "https://applink/..";
await _apiService.AddNotifyFirebase(devicetoken, titlefirebase, bodyfirebase, linkfirebase);
}
public async Task AddNotifyFirebase(string devicetoken, string titlefirebase, string bodyfirebase, string linkfirebase)
{
var model = new
{
devicetoken = devicetoken,
titlefirebase = titlefirebase,
bodyfirebase = bodyfirebase,
linkfirebase = linkfirebase,
};
var json = JsonConvert.SerializeObject(model);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, "https://linkapi/api/SendNotifyDeviceFirebase");
request.Content = content;
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
}
}
However I get the error: StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.NSUrlSessionHandler+NSUrlSessionDataTaskStreamContent, ....
Where did I go wrong? Looking forward to everyone's help. Thank you!
Update
I check on Swagger:
Everything seems fine!
I then changed the send command back:
public async Task AddNotifyFirebase(string devicetoken, string titlefirebase, string bodyfirebase, string linkfirebase)
{
var request = new HttpRequestMessage(HttpMethod.Post, "https://xxxxxx/api/SendNotifyDeviceFirebase?deviceTokens=" + devicetoken + "&title=" + titlefirebase + "&body=" + bodyfirebase + "&linkdirection=" + linkfirebase);
//request.Headers.Add("Accept-Encoding", "gzip");
//request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain; charset=utf-8");
HttpResponseMessage response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
}
}
I get the error again: StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'
I have handled the problem. Thank you all
public async Task AddNotifyFirebase(NotifyFireBase NotifyFireBaseAdd)
{
var urlput = "......";
HttpClient client = new HttpClient();
var content = NotifyFireBaseAdd;
var stringContent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");
await client.PostAsync(urlput, stringContent);
}
I'm calling API using HttpClient below code running fine on localhost but when it's live on server it's return html response.
here is the code i'm using
public async Task<ActionResult> getPost()
{
string url = "https://www.instagram.com/p/Bg9DwFYHARK/?__a=1";
HttpClient _client = new HttpClient();
var Response = await _client.GetAsync(url);
if (Response.IsSuccessStatusCode)
{
var Result = Response.Content.ReadAsStringAsync().Result;
//here in **Result** i've received html instead of json or when i received html instead
of json got error on DeserializeObject.
var Jsonresult = JsonConvert.DeserializeObject<post>(Result);
return Json(new { isValid = false, error = "post found", obj = Jsonresult }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { isValid = false, error = "post not found" }, JsonRequestBehavior.AllowGet);
}
}
This method response is JSON.
string uri = "https://www.instagram.com/p/Bg9DwFYHARK/?__a=1";
private static async Task<ActionResult> getPost(string uri)
{
var webRequest = WebRequest.Create(uri) as HttpWebRequest;
if (webRequest == null)
{
return;
}
webRequest.ContentType = "application/json";
webRequest.UserAgent = "Nothing";
using (var s = webRequest.GetResponse().GetResponseStream())
{
using (var sr = new StreamReader(s))
{
// var contributorsAsJson = sr.ReadToEnd();
var contributors = JsonConvert.DeserializeObject<Create a list >(contributorsAsJson);
// contributors.ForEach(Console.WriteLine);
return contributors;
}
}
}
I get out put is:
{"graphql":{"shortcode_media":{"__typename":"GraphImage","id":"1746568728937235530","shortcode":"Bg9DwFYHARK","dimensions":{"height":1080,"width":1080},"gating_info":null,"fact_check_overall_rating":null,"fact_check_information":null,"sensitivity_friction_info":null,"media_overlay_info":null,"media_preview":"ACoqytpjBOM+tQs6t07nvxwOn4889q2TDuGKzrfT2kkKtkBDz7j2PT0/OlpuUm7cvQqrbSS/cBb6D/IqI8DHfvXZiVI12qpBA+7xwPr0/WueMXm3LMBx94jryf0PrSTdwaVrlSKMsKd5ZrYji7n8B/8AWp3k+wp3ILSKT0FBkW2YM/AcEZ9xz+o4+uBVgyBSB26VDcWgnYFuVUEbfr3B9Qarl0HcRrgqQWVlX5snjIBxgsOw9fTFR2xEu+QdHbj6DgH8earPayvuUuXXHTGC2OgZv5461pQRGKNY+PlABx69/wBamKvuVJ9iMgikqwy4qPZSasJambblpm3dlP5n69x/9atgetZ1h/qV/H+ZrQHQfhWl7tk2JqY7bQT6UtRvTAN2aZUSnn8am2L6D8qdk9xbH//Z","display_url":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-15/e35/29400587_173904939930435_4131401846013034496_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=cgtRDraKPGoAX_a9AvI&oh=fc8640215bbe4a5003bbaf694113951c&oe=5F2FFE5A","display_resources":[{"src":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-15/sh0.08/e35/s640x640/29400587_173904939930435_4131401846013034496_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=cgtRDraKPGoAX_a9AvI&oh=e971123fdc4eb19abe4a96b35195dd9f&oe=5F30CFBD","config_width":640,"config_height":640},{"src":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-15/sh0.08/e35/s750x750/29400587_173904939930435_4131401846013034496_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=cgtRDraKPGoAX_a9AvI&oh=33fe7c336ecff4205e161452adfc7ecf&oe=5F31703D","config_width":750,"config_height":750},{"src":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-15/e35/29400587_173904939930435_4131401846013034496_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=cgtRDraKPGoAX_a9AvI&oh=fc8640215bbe4a5003bbaf694113951c&oe=5F2FFE5A","config_width":1080,"config_height":1080}],"accessibility_caption":"Photo by Ateeq Khalil in Salt N Pepper Liberty. Image may contain: 1 person","is_video":false,"tracking_token":"eyJ2ZXJzaW9uIjo1LCJwYXlsb2FkIjp7ImlzX2FuYWx5dGljc190cmFja2VkIjp0cnVlLCJ1dWlkIjoiZWQ2ZjUxNTZjMjc5NDU5MzlmMmQ1MTQzZDBhZmIyYjYxNzQ2NTY4NzI4OTM3MjM1NTMwIn0sInNpZ25hdHVyZSI6IiJ9","edge_media_to_tagged_user":{"edges":[]},"edge_media_to_caption":{"edges":[]},"caption_is_edited":false,"has_ranked_comments":false,"edge_media_to_parent_comment":{"count":0,"page_info":{"has_next_page":false,"end_cursor":null},"edges":[]},"edge_media_to_hoisted_comment":{"edges":[]},"edge_media_preview_comment":{"count":0,"edges":[]},"comments_disabled":false,"commenting_disabled_for_viewer":false,"taken_at_timestamp":1522427239,"edge_media_preview_like":{"count":19,"edges":[]},"edge_media_to_sponsor_user":{"edges":[]},"location":{"id":"1730525857251432","has_public_page":true,"name":"Salt N Pepper Liberty","slug":"salt-n-pepper-liberty","address_json":"{\"street_address\": \"48 Commercial Zone Liberty Market, Gulberg III\\u060c\", \"zip_code\": \"\", \"city_name\": \"Lahore, Pakistan\", \"region_name\": \"\", \"country_code\": \"PK\", \"exact_city_match\": false, \"exact_region_match\": false, \"exact_country_match\": false}"},"viewer_has_liked":false,"viewer_has_saved":false,"viewer_has_saved_to_collection":false,"viewer_in_photo_of_you":false,"viewer_can_reshare":true,"owner":{"id":"5394358177","is_verified":false,"profile_pic_url":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-19/s150x150/29402856_149619235868663_6235876322871083008_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_ohc=gSyry9Wj5UkAX_bQlzD&oh=bdc6a6b82077c8e461aedbaffa7e49db&oe=5F32308B","username":"ateeq.khalil","blocked_by_viewer":false,"restricted_by_viewer":null,"followed_by_viewer":false,"full_name":"Ateeq Khalil","has_blocked_viewer":false,"is_private":false,"is_unpublished":false,"requested_by_viewer":false,"edge_owner_to_timeline_media":{"count":7},"edge_followed_by":{"count":175}},"is_ad":false,"edge_web_media_to_related_media":{"edges":[]},"edge_related_profiles":{"edges":[]}}}}
I'm trying to access data through an API call. The authentication requirement is:
The authentication token needs to be passed as a header in the calls under the header name ACCESS-TOKEN.
NOTE: Add Content-Type as Application/JSON
var uri = new Uri(string.Format("https://stg-api.oyorooms.ms/api/v2/hotels/get_availability/"));
var json = JsonConvert.SerializeObject(action);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
if (isNewItem)
{
// client.BaseAddress = new Uri("https://stg-api.oyorooms.ms/api/v2/hotels/get_availability/");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("ACCESS-TOKEN", "c19.....j5XeS0=");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
request.Content = new StringContent(content.ToString(),
Encoding.UTF8,
"application/json");
response = client.PostAsync(uri, content).Result;
resp = response.Content.ToString();//for getting break points
}
var resp1 = response.Content.ToString();//for getting break points
if (response.IsSuccessStatusCode)
{
string responsedone = await response.Content.ReadAsStringAsync();
var Items = JsonConvert.DeserializeObject<List<OyoSearchData>>(responsedone);
var ids = Items[0].Hotels.Hotel[0].ID;
}
The response I got was:
{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Connection: close, Transfer-Encoding
Date: Sat, 22 Jun 2019 05:33:41 GMT
Server: nginx/1.14.1
Transfer-Encoding: chunked
X-Android-Received-Millis: 1561181624449
X-Android-Response-Source: NETWORK 401
X-Android-Selected-Protocol: http/1.1
X-Android-Sent-Millis: 1561181624232
Content-Type: application/json;charset=UTF-8
}}
Why am I getting this error? Is my access token is not being sent along with the headers? Please help.
Other code I tried was:
public async Task GetOyoApiDataCall(OyoHotelavailability action, bool isNewItem = false)
{
string resp = null;
try
{
var uri = new Uri(string.Format("https://stg-api.oyorooms.ms/api/v2/hotels/get_availability/"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("ACCESS-TOKEN", "c19.......W5XeS0=");
var json = JsonConvert.SerializeObject(action);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
if (isNewItem)
{
response = client.PostAsync(uri, content).Result;
resp = response.Content.ToString();//for getting break points
}
var resp1 = response.Content.ToString();//for getting break points
if (response.IsSuccessStatusCode)
{
string responsedone = await response.Content.ReadAsStringAsync();
var Items = JsonConvert.DeserializeObject<List<OyoSearchData>>(responsedone);
var ids = Items[0].Hotels.Hotel[0].ID;
}
}
catch (Exception e)
{
}
}
Getting same error.
Your problem is that based on your code, you aren't actually setting a HTTP header of the form:
ACCESS-TOKEN: c19.......W5XeS0=
Based on the line of code client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("ACCESS-TOKEN", "c19.......W5XeS0=");, what you're doing is creating a header of the form:
Authorization: ACCESS-TOKEN c19.......W5XeS0=
Instead, you need to add a custom header called ACCESS-TOKEN. There is a nice answer on the subject by #LibinJoseph. Basically, you just need to substitute your problematic line with a line of the form:
client.DefaultRequestHeaders.Add("ACCESS-TOKEN","c19.......W5XeS0=");
I hope that helps!
I want to send file through post request using httpclient
this what i tried but file didn't sent , when i tried in postman it works fine
string Url = $"http://ataprojects.net/test/products.php?request_type=add&company_name={BaseService.Company}&name={product.name}&barcode={product.barcode}&buy_price={product.buy_price}&sell_price={product.sell_price}";
try
{
using (HttpClient client = new HttpClient())
{
var content = new MultipartFormDataContent();
content.Headers.ContentType.MediaType = "multipart/form-data";
content.Add(new StreamContent(product._mediaFile.GetStream()),
"image",
product.image);
var response = client.PostAsync(Url, content).Result;
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
var contentdata = await response.Content.ReadAsStringAsync();
var Items = JsonConvert.DeserializeObject<AddProductReturnModel>(contentdata);
return Items;
}
else
{
return null;
}
}
}
what's the problem ?
Try This Code
var content = new MultipartFormDataContent();
content.Add(new StreamContent(product._mediaFile.GetStream()),
"\"file\"",
$"\"{product._mediaFile.Path}\"");
Good morning, I want to send data by get through esp8266, I have a qualifying account in byethost and I also have a hosting account paid with another hosting provider, but with byethost I get the following error:
AT+CIPSTART="TCP","ahorrodeenergy.byethost17.com",80
AT+CIPSEND=67
GET /inserta.php HTTP/1.1
Host:ahorrodeenergy.byethost17.com/inserta.php"
+IPD,1080:HTTP/1.1 200 OK
Server: nginx
Date: Fri, 10 Mar 2017 01:30:09 GMT
Content-Type: text/html
Content-Length: 851
Connection: keep-alive
Vary: Accept-Encoding
Expires: THu, 01 Jan 1970 00:00:01 GMT
Cache-Control: no-cache
And returns: This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support
Spoof the User-Agent string. It probably tries to identify your browser by that, and then tries to figure out if you have JavaScript enabled. It could then try to use more active tests, like inserting a piece of JavaScript and expect a page to be called with the result of the computation of that javascript, in a challenge-and-response manner. But I think a User-Agent spoof should just work fine. Do the following:
AT+CIPSTART="TCP","ahorrodeenergy.byethost17.com",80
AT+CIPSEND=154
GET /inserta.php HTTP/1.1
Host: ahorrodeenergy.byethost17.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0
+IPD,1080: ..
(number in CIPSEND assumes \r\nbeing used as newline)
Based on the this awnser, the problem is testcookie-nginx-module which is used by byethost, and here the solution:
/*
Author: Moien007
Source: https://gist.github.com/moien007/06656aa4032c45b629a507dd4dcb6fd6
Description:
Bypass testcookie-nginx-module bot protection
Web host providers like Byethost uses that module so...
*/
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Net;
using System.Net.Http;
namespace Gist
{
class CustomWebClient
{
const string TestCookieSign = "aes.js";
public static byte[] Get(string url)
{
var address = new Uri(url);
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler))
{
var content = client.GetAsync(address).WaitResult().Content;
var script = content.ReadAsStringAsync().WaitResult();
if (!script.Contains(TestCookieSign))
{
return content.ReadAsByteArrayAsync().WaitResult();
}
var test = Decrypt(script);
cookieContainer.Add(new Cookie("__test", test) { Domain = address.Host });
content = client.GetAsync(address).WaitResult().Content;
if (content.ReadAsStringAsync().WaitResult().Contains(TestCookieSign))
{
throw new Exception();
}
return content.ReadAsByteArrayAsync().WaitResult();
}
}
public static byte[] Post(string url, byte[] data)
{
var address = new Uri(url);
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler))
using (var post = new ByteArrayContent(data))
{
var content = client.PostAsync(address, post).WaitResult().Content;
var script = content.ReadAsStringAsync().WaitResult();
if (!script.Contains(TestCookieSign))
{
return content.ReadAsByteArrayAsync().WaitResult();
}
var test = Decrypt(script);
cookieContainer.Add(new Cookie("__test", test) { Domain = address.Host });
content = client.PostAsync(address, post).WaitResult().Content;
if (content.ReadAsStringAsync().WaitResult().Contains(TestCookieSign))
{
throw new Exception();
}
return content.ReadAsByteArrayAsync().WaitResult();
}
}
static string Decrypt(string script)
{
var split = script.Split(new[] { "toNumbers(\"", "\")" }, StringSplitOptions.RemoveEmptyEntries)
.Where(s => s.Length == 32)
.ToArray();
if (split.Length != 3)
throw new Exception();
var key = StringToByteArray(split[0]);
var iv = StringToByteArray(split[1]);
var bytesIn = StringToByteArray(split[2]);
var aes = Aes.Create();
aes.Padding = PaddingMode.None;
aes.Mode = CipherMode.CBC;
aes.BlockSize = 128;
aes.KeySize = 128;
aes.Key = key;
aes.IV = iv;
var decrypter = aes.CreateDecryptor();
var decrypted = decrypter.TransformFinalBlock(bytesIn, 0, bytesIn.Length);
decrypter.Dispose();
aes.Dispose();
return BitConverter.ToString(decrypted).Replace("-", "").ToLower();
}
static byte[] StringToByteArray(string hex) // Taken from https://stackoverflow.com/a/321404/9248173
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
}
static class ExtensionMethods
{
public static T WaitResult<T>(this Task<T> task)
{
task.Wait();
return task.Result;
}
}
}