esp8266 byethost Error get request - nginx

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;
}
}
}

Related

How can I make proper request for the Identity Server Token Endpoint?

I tried to send an api call to the identity server via .net 6 console application.
Here is the request:
public static async Task<WorkflowResponse> PostRequestToIdentityAsync()
{
var url = "http://didentity/connect/token";
IdentityRequestDataVM identityRequestDataVM = new IdentityRequestDataVM();
identityRequestDataVM.username = "csm";
identityRequestDataVM.password = "MjAyMjox";
identityRequestDataVM.grant_type = "password";
identityRequestDataVM.scope = "m_gln m_msd";
string jsonString = JsonConvert.SerializeObject(identityRequestDataVM);
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Content = new StringContent(jsonString),
Headers =
{
{"X-Login","override"}
}
};
var user = "gclt";
var password = "glsrt";
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes($"{user}:{password}")));
HttpResponseMessage message = await httpClient.SendAsync(request);
if (message.StatusCode == System.Net.HttpStatusCode.OK)
{
var contents = await message.Content.ReadAsStringAsync();
WorkflowResponse workflowResponse = JsonConvert.DeserializeObject<WorkflowResponse>(contents);
return workflowResponse;
}
else
{
throw new Exception(await message.Content.ReadAsStringAsync());
}
}
}
But, it returned 400 err code (Bad request), is there any mistake in the code snippet ?
It is working fine with postman.

Reverse proxy in .NET Core Middleware “set-cookie” response does not set in browser and not showing in HttpResponseMessage

Here I am making a reverse proxy server to bypass an ASP.NET web application (following this tutorial). I am trying to read the session ID cookie from HttpResponseMessage. I used a cookie container as well but am unable to find it. Implemented in ASP.NET core invoke method, session is working properly but unable to catch session ID in request or response.
public async Task Invoke(HttpContext context, IBrowserDetector detector)
{
//context.Session.SetString(SessionKeyName, "The Doctor");
var browser = detector.Browser;
var targetUri = BuildTargetUri(context.Request);
if (context.Request.Method != HttpMethod.Get.Method)
{
var remoteIp = context.Connection.RemoteIpAddress;
//var gg= context.Request.Headers.ContainsKey.;
var clienttdatetime = context.Request.Headers["Date"].ToString();
//_logger.LogDebug("Request from Remote IP address: {RemoteIp}", remoteIp);
var badIp = true;
var bytes = remoteIp.GetAddressBytes();
//var testIp = IPAddress.Parse(address);
//if (testIp.GetAddressBytes().SequenceEqual(bytes))
//{
// badIp = false;
// break;
//}
if (remoteIp.IsIPv4MappedToIPv6)
{
remoteIp = remoteIp.MapToIPv4();
}
IPAddress remoteIpAddress = context.Request.HttpContext.Connection.RemoteIpAddress;
string result = "";
if (remoteIpAddress != null)
{
// If we got an IPV6 address, then we need to ask the network for the IPV4 address
// This usually only happens when the browser is on the same machine as the server.
if (remoteIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
remoteIpAddress = System.Net.Dns.GetHostEntry(remoteIpAddress).AddressList
.First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
}
result = remoteIpAddress.ToString();
}
if (badIp)
{
//_logger.LogWarning(
// "Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);
//context.Response.StatusCode = StatusCodes.Status403Forbidden;
//return;
}
}
if (targetUri != null)
{
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
var targetRequestMessage = CreateTargetMessage(context, targetUri);
using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
foreach (Cookie cookie_ in responseCookies)
Console.WriteLine(cookie_.Name + ": " + cookie_.Value);
// ExtractCookiesFromResponse(responseMessage);
context.Response.StatusCode = (int)responseMessage.StatusCode;
CopyFromTargetResponseHeaders(context, responseMessage);
await responseMessage.Content.CopyToAsync(context.Response.Body);
//if(responseMessage.RequestMessage.RequestUri.ToString()== "http://localhost:51125/Menu.aspx")
//{
//Uri uri = new Uri("http://localhost:5000/login.aspx");
//Build the request
//Uri site = targetUri;
// HttpWebRequest request = (HttpWebRequest)WebRequest.Create(site);
// CookieContainer cookiesq = new CookieContainer();
// request.CookieContainer = cookiesq;
// //Print out the number of cookies before the response (of course it will be blank)
// Console.WriteLine(cookiesq.GetCookieHeader(site),"1");
// //Get the response and print out the cookies again
// using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
// {
// Console.WriteLine(cookiesq.GetCookieHeader(site), "2");
// }
// Console.ReadKey();
//}
var cookie = context.Request.Cookies["ASP.NET_SessionId"];
}
return;
}
await _nextMiddleware(context);
}
------------------------------------------------------------------------------------
public static IDictionary<string, string> ExtractCookiesFromResponse(HttpResponseMessage response)
{
IDictionary<string, string> result = new Dictionary<string, string>();
IEnumerable<string> values;
if (response.Headers.TryGetValues("Set-Cookie", out values))
{
SetCookieHeaderValue.ParseList(values.ToList()).ToList().ForEach(cookie =>
{
result.Add(cookie.Name.ToString(), cookie.Value.ToString());
});
}
return result;
}
As far as I can see, you created the HttpClientHandler but didn't use it to build the HttpClient to make your request. You are still using the static _httpClient that nothing knows about the cookie container you created.
This should be the reason why you get the CookieContainer still empty.
Take a look here to learn how to get cookies from an HttpResponseMessage.
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
_httpClient = new HttpClient(handler);
var targetRequestMessage = CreateTargetMessage(context, targetUri);
using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
//var responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
{
if(cookie.Name=="ASP.NET_SessionId")
{
Console.WriteLine(cookie.Name + ": " + cookie.Value);
context.Response.Headers.Add("Set-Cookie", cookie.Name+"="+cookie.Value);
}
}

HttpClient return json response on localhost when application live on server it's return html

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":[]}}}}

how to solve Http 401 error,but working in postman,not working in xamarin forms

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!

asp.net Web API file upload fileData empty

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
}

Resources