I am trying to receive one simple sentence from a webservice, but I have something wrong.
This is my async task to request from the webservice:
private async Task<string> GetData (string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (new Uri(url));
request.ContentType = "text/plain";
request.Method = "GET";
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream stream = response.GetResponseStream())
{
string doc = await Task.Run(() => stream.ToString());
return doc;
}
}
}
And this is my button:
cmd02.Click += async (sender, e) => {
string sentence = await GetData(url);
txt01.Text = sentence;
};
I get only "System.Net.WebConnectionStream" into my TextView and donĀ“t know which function I should use. Or maybe everthing is wrong?
Maybe somebody has an idea?
public static async Task<string> SendGetRequestAsync (string url) {
string responseString = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response;
await Task.Run (() => {
try {
response = request.GetResponse () as HttpWebResponse;
using (var reader = new StreamReader (response.GetResponseStream ())) {
responseString = reader.ReadToEnd ();
}
} catch (WebException ex) {
Console.WriteLine (ex);
}
});
return responseString;
}
Related
I want to embed novnc console in an iframe into a .net web application. My openstack is configured to recieve http requests and my web application sends https requests.
When I use iframe to show my novnc console in asp.net web application, the console sends WSS request to my server but the openstack horizon accepts WS requests, because of that I create a middleware to convert requests from https to http & WSS to WS but it didn't work, I don't know what is the problem, my console is shown but the connection is closed immediately.
my reverse proxy for handle http request is:
namespace ReverseProxyApplication
{
public class ReverseProxyMiddleware
{
private static readonly HttpClient _httpClient = new HttpClient();
private readonly RequestDelegate _nextMiddleware;
public ReverseProxyMiddleware(RequestDelegate nextMiddleware)
{
_nextMiddleware = nextMiddleware;
}
public async Task Invoke(HttpContext context)
{
var targetUri = BuildTargetUri(context.Request);
if (targetUri != null)
{
var targetRequestMessage = CreateTargetMessage(context, targetUri);
using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
context.Response.StatusCode = (int)responseMessage.StatusCode;
CopyFromTargetResponseHeaders(context, responseMessage);
await responseMessage.Content.CopyToAsync(context.Response.Body);
}
return;
}
await _nextMiddleware(context);
}
private HttpRequestMessage CreateTargetMessage(HttpContext context, Uri targetUri)
{
var requestMessage = new HttpRequestMessage();
CopyFromOriginalRequestContentAndHeaders(context, requestMessage);
requestMessage.RequestUri = targetUri;
requestMessage.Headers.Host = targetUri.Host;
requestMessage.Method = GetMethod(context.Request.Method);
return requestMessage;
}
private void CopyFromOriginalRequestContentAndHeaders(HttpContext context, HttpRequestMessage requestMessage)
{
var requestMethod = context.Request.Method;
if (!HttpMethods.IsGet(requestMethod) &&
!HttpMethods.IsHead(requestMethod) &&
!HttpMethods.IsDelete(requestMethod) &&
!HttpMethods.IsTrace(requestMethod))
{
var streamContent = new StreamContent(context.Request.Body);
requestMessage.Content = streamContent;
}
foreach (var header in context.Request.Headers)
{
requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
}
}
private void CopyFromTargetResponseHeaders(HttpContext context, HttpResponseMessage responseMessage)
{
foreach (var header in responseMessage.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray();
}
foreach (var header in responseMessage.Content.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray();
}
context.Response.Headers.Remove("transfer-encoding");
}
private static HttpMethod GetMethod(string method)
{
if (HttpMethods.IsDelete(method)) return HttpMethod.Delete;
if (HttpMethods.IsGet(method)) return HttpMethod.Get;
if (HttpMethods.IsHead(method)) return HttpMethod.Head;
if (HttpMethods.IsOptions(method)) return HttpMethod.Options;
if (HttpMethods.IsPost(method)) return HttpMethod.Post;
if (HttpMethods.IsPut(method)) return HttpMethod.Put;
if (HttpMethods.IsTrace(method)) return HttpMethod.Trace;
return new HttpMethod(method);
}
private Uri BuildTargetUri(HttpRequest request)
{
Uri targetUri = null;
if (request.Path.StartsWithSegments("/horizon", out var remainingPath))
{
targetUri = new Uri("http://192.168.66.11:6080" + remainingPath);
}
return targetUri;
}
}
}
and my web socket middle ware
public class WebSocketMiddleware
{
private static ConcurrentDictionary<string, WebSocket> _sockets = new ConcurrentDictionary<string, WebSocket>();
private readonly RequestDelegate _next;
public WebSocketMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (!context.WebSockets.IsWebSocketRequest)
{
await _next.Invoke(context);
return;
}
var buffer = new ArraySegment<byte>(new byte[8192]);
Uri targetUri = new Uri("ws://192.168.66.11:6080/" + context.Request.QueryString.Value);
ClientWebSocket _websocketClient = new ClientWebSocket();
await _websocketClient.ConnectAsync(targetUri, CancellationToken.None);
// if (_websocketClient.State == WebSocketState.Open)
// {
// // await _websocketClient.SendAsync(buffer, WebSocketMessageType.Binary, true, CancellationToken.None);
// var result = await _websocketClient.ReceiveAsync(buffer, CancellationToken.None);
// if (result.MessageType == WebSocketMessageType.Close)
// {
// await _websocketClient.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
// }
// }
CancellationToken ct = context.RequestAborted;
WebSocket currentSocket = await context.WebSockets.AcceptWebSocketAsync();
var socketId = Guid.NewGuid().ToString();
_sockets.TryAdd(socketId, currentSocket);
foreach (var socket in _sockets)
{
if (socket.Value.State != WebSocketState.Open)
{
continue;
}
await SendStringAsync(socket.Value, _websocketClient, buffer, ct);
}
while (true)
{
if (ct.IsCancellationRequested)
{
break;
}
var response = await ReceiveStringAsync(currentSocket, _websocketClient, context, ct);
if (response != null)
{
if (currentSocket.State != WebSocketState.Open)
{
break;
}
//continue;
foreach (var socket in _sockets)
{
if (socket.Value.State != WebSocketState.Open)
{
continue;
}
await SendStringAsync(socket.Value, _websocketClient, response, ct);
}
}
}
WebSocket dummy;
_sockets.TryRemove(socketId, out dummy);
await currentSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", ct);
currentSocket.Dispose();
}
private static Task SendStringAsync(WebSocket socket, ClientWebSocket _websocketClient, ArraySegment<byte> data, CancellationToken ct = default(CancellationToken))
{
//var buffer = Encoding.UTF8.GetBytes(data);
var segment = new ArraySegment<byte>(new byte[8192]);
if (_websocketClient.State == WebSocketState.Open)
{
_websocketClient.ReceiveAsync(segment, CancellationToken.None);
//_websocketClient.SendAsync(segment, WebSocketMessageType.Binary, true, CancellationToken.None);
}
return socket.SendAsync(segment, WebSocketMessageType.Binary, true, ct);
}
private static async Task<ArraySegment<byte>> ReceiveStringAsync(WebSocket socket, ClientWebSocket _websocketClient, HttpContext context, CancellationToken ct = default(CancellationToken))
{
var buffer = new ArraySegment<byte>(new byte[8192]);
WebSocketReceiveResult result;
do
{
ct.ThrowIfCancellationRequested();
result = await socket.ReceiveAsync(buffer, ct);
} while (!result.EndOfMessage);
// Uri targetUri = new Uri("ws://192.168.66.11:6080/" + context.Request.QueryString.Value);
//ClientWebSocket _websocketClient = new ClientWebSocket();
//await _websocketClient.ConnectAsync(targetUri, CancellationToken.None);
if (_websocketClient.State == WebSocketState.Open)
{
bool hasAllZeroes = buffer.All(singleByte => singleByte == 0);
if (!hasAllZeroes)
await _websocketClient.SendAsync(buffer, WebSocketMessageType.Binary, true, CancellationToken.None);
//var myresult = await _websocketClient.ReceiveAsync(buffer, CancellationToken.None);
}
return buffer == new ArraySegment<byte>(new byte[8192]) ? null : buffer;
}
}
when i load the page this is my wss request
novnc console in i frame
js errors
wss request to middle ware
.
Use the IHttpForwarder from YARP https://microsoft.github.io/reverse-proxy/articles/direct-forwarding.html. It handles websocket, grpc etc etc.
var appCredentials = new FitbitAppCredentials()
{
ClientId = "227RD5", //ConfigurationManager.AppSettings["FitbitClientId"],
ClientSecret = "468c585ba98fc84e463952ca7a306c07" //ConfigurationManager.AppSettings["FitbitClientSecret"]
};
string UserId = Convert.ToBase64String((Encoding.ASCII.GetBytes("3J9685")));
string code = Request.Params["code"];
StringBuilder dataRequestUrl = new StringBuilder();
dataRequestUrl.Append("https://api.fitbit.com/1/user/-");
dataRequestUrl.Append("/profile.json");
HttpWebRequest dataRequest = (HttpWebRequest)WebRequest.Create(dataRequestUrl.ToString());
dataRequest.Method = "POST";
string _auth = string.Format("{0}:{1}", appCredentials.ClientId, appCredentials.ClientSecret);
var _encbyte = Encoding.ASCII.GetBytes(_auth);
string _enc = Convert.ToBase64String(_encbyte);
string _authorizationHeader = string.Format("{0} {1}", "Bearer", _enc);
dataRequest.Headers["Authorization"] = _authorizationHeader;
dataRequest.ContentType = "application/x-www-form-urlencoded";
dataRequest.Accept = "application/json";
string responseJson;
HttpWebResponse response = null;
try
{
response = dataRequest.GetResponse() as HttpWebResponse;
}
catch (WebException webEx)
{
response = webEx.Response as HttpWebResponse;
}
catch (Exception ex)
{
throw ex;
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseJson = reader.ReadToEnd();
}
Above code give me unauthorized access error. Any one can find that what is the issue in code.I can authorize the user and refresh the user token but when I will try to get userprofile.json call it will give me unauthorized access error.
For getting user profile information, we need only access-token sent as part of header.
You don't need clientId and ClientSecret for getting profile information.
Change your code like this:
StringBuilder dataRequestUrl = new StringBuilder();
dataRequestUrl.Append("https://api.fitbit.com/1/user/-/profile.json");
HttpWebRequest dataRequest = (HttpWebRequest)WebRequest.Create(dataRequestUrl.ToString());
String accessToken = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiXXXXXXXXXX";
dataRequest.Method = "GET";
dataRequest.Headers.Add("Authorization","Bearer "+ accessToken);
dataRequest.ContentType = "application/json";
string responseJson;
HttpWebResponse response = null;
try
{
response = dataRequest.GetResponse() as HttpWebResponse;
}
catch (WebException webEx)
{
response = webEx.Response as HttpWebResponse;
}
catch (Exception ex)
{
throw ex;
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseJson = reader.ReadToEnd();
}
If I want do add a item into the TableView then the loop must be stopped. But I have a WebResponse and by every HTTP Chunked the TableView need a new item.
Did anyone have a solution to add a item into a TableView without to stop the while loop?
this is my Thread
new System.Threading.Thread(new System.Threading.ThreadStart(() =>
{
InvokeOnMainThread(() =>
{
HttpRequest t = new HttpRequest(TableView, source);
t.Start();
});
})).Start();
And this is my loop:
WebResponse webResponse = web.GetResponse();
Stream stream = webResponse.GetResponseStream();
var reader = new XmlTextReader(stream);
string telegram = "";
int check = 0;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
break;
case XmlNodeType.Text:
break;
case XmlNodeType.EndElement:
break;
}
}
and in a funtion in the loop I do this
(tableView.Source as TelegrammSource).AddTelegramm(details);
tableView.ReloadData();
There a sample to finish async data requesting and refresh your tableview:
string strURL = "https://api.bitcoinaverage.com/ticker/";
MyHTTPRequestManager.Instance.GetDataFromUrl (strURL,(string dataStr)=>{
Console.WriteLine("Getting data succeed");
Console.WriteLine("The dataStr = "+dataStr);
//update your dataList here
InvokeOnMainThread(delegate {
//Update your tableView or collectionView here, all UI stuff must be invoke on Main thread
});
});
And this is the MyHTTPRequestManager.cs:
public class MyHTTPRequestManager
{
public delegate void GettingDataCallback(string dataStr);
private static MyHTTPRequestManager instance = null;
public static MyHTTPRequestManager Instance{
get{
if(null == instance)
instance = new MyHTTPRequestManager();
return instance;
}
}
public void GetDataFromUrl(string strURL,GettingDataCallback callback)
{
Console.WriteLine ("Begin request data.");
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseText = myreader.ReadToEnd();
myreader.Close();
Console.WriteLine ("Getting succeed, invoke callback.");
callback.Invoke (responseText);
}
}
Hope it can help you.
This is my ViewDidLoad on the TableviewController
base.ViewDidLoad();
Console.Out.WriteLine("ViewDidLoad");
TableView.SeparatorColor = UIColor.Black;
TableView.SeparatorStyle = UITableViewCellSeparatorStyle.SingleLine;
source = new TelegrammSource();
TableView.Source = source;
new System.Threading.Thread(new System.Threading.ThreadStart(() =>
{
InvokeOnMainThread(() =>
{
HttpRequest t = new HttpRequest(TableView, source);
t.Start();
});
})).Start();
And this is my HttpRequest
public class HttpRequest
{
//private volatile bool _shouldStop;
public string url = "";
private HttpWebRequest web = null;
readonly UITableView tableView;
public HttpRequest(UITableView tableView, TelegrammSource source)
{
this.tableView = tableView;
url = "http://www.example.com";
web = (HttpWebRequest)WebRequest.Create(url);
web.Credentials = new NetworkCredential((kanalsettings[(NSString)GlobaleVariablen.KE_BENUTZERNAME] as NSString), (kanalsettings[(NSString)GlobaleVariablen.KE_PASSWORT] as NSString));
}
public void Start()
{
WebResponse webResponse = web.GetResponse();
Stream stream = webResponse.GetResponseStream();
var reader = new XmlTextReader(stream);
string telegram = "";
int check = 0;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
break;
case XmlNodeType.Text:
break;
case XmlNodeType.EndElement:
Process(telegram);
break;
}
}
}
public void Process(string result)
{
var details = new TelegrammDetails();
var xml = new XmlDocument();
xml.LoadXml(result);
XmlNodeList telegram = xml.SelectNodes("/");
foreach (XmlNode item in telegram)
{
}
(tableView.Source as TelegrammSource).AddTelegramm(details);
tableView.ReloadData();
}
}
I'm develop a web api2 where I post json data.
The code of this api is:
public HttpResponseMessage Post(an_lavanderie an_lavanderie)
{
var response = new HttpResponseMessage();
if (!ModelState.IsValid)
{
response = Request.CreateErrorResponse(HttpStatusCode.NotFound, new Exception("modello non valido"));
}
bool creato = _repoLavanderie.CreaLavanderia(an_lavanderie);
if (creato == true)
{
response = Request.CreateResponse(HttpStatusCode.OK);
}
else
{
response = Request.CreateErrorResponse(HttpStatusCode.NotFound, new Exception("Errore nella creazione"));
}
return response;
}
This code write into db correctly.
My code to POST DATA is this:
var risultato = PostDataAsync();
and the function is
var lav1 = new Lavanderia()
{
rag_soc = "Ragione Sociale",
rag_soc2 = "Ragione sociale2",
indirizzo = "Via Crispi 27",
citta = "Ovada",
provincia = "AL",
isAttiva = "N",
portalkey = "sample string 1",
isPortalVisibile = "S",
cap = "15057"
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:56040/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync("api/CreaLavanderia", lav1);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
MessageBox.Show("Crezione effettuata correttamente");
}
else
{
MessageBox.Show("Creazione non effettuata");
}
}
return "";
Post operation is ok, but when await don't fire.
Is possible that the return Message from webapi is not correct?
Where is the problem?
Thanks.
Since you are using await and you're saying that it's not firing make sure that your method is marked with the keyword async.
On ASP.NET MVC, I try to write an async Controller action with the old asynchronous programming model (actually, it is the current one, new one is still a CTP).
Here, I am trying to run 4 operations in parallel and it worked great. Here is the complete code:
public class SampleController : AsyncController {
public void IndexAsync() {
AsyncManager.OutstandingOperations.Increment(4);
var task1 = Task<string>.Factory.StartNew(() => {
return GetReponse1();
});
var task2 = Task<string>.Factory.StartNew(() => {
return GetResponse2();
});
var task3 = Task<string>.Factory.StartNew(() => {
return GetResponse3();
});
var task4 = Task<string>.Factory.StartNew(() => {
return GetResponse4();
});
task1.ContinueWith(t => {
AsyncManager.Parameters["headers1"] = t.Result;
AsyncManager.OutstandingOperations.Decrement();
});
task2.ContinueWith(t => {
AsyncManager.Parameters["headers2"] = t.Result;
AsyncManager.OutstandingOperations.Decrement();
});
task3.ContinueWith(t => {
AsyncManager.Parameters["headers3"] = t.Result;
AsyncManager.OutstandingOperations.Decrement();
});
task4.ContinueWith(t => {
AsyncManager.Parameters["headers4"] = t.Result;
AsyncManager.OutstandingOperations.Decrement();
});
task3.ContinueWith(t => {
AsyncManager.OutstandingOperations.Decrement();
}, TaskContinuationOptions.OnlyOnFaulted);
}
public ActionResult IndexCompleted(string headers1, string headers2, string headers3, string headers4) {
ViewBag.Headers = string.Join("<br/><br/>", headers1, headers2, headers3, headers4);
return View();
}
public ActionResult Index2() {
ViewBag.Headers = string.Join("<br/><br/>", GetReponse1(), GetResponse2(), GetResponse3(), GetResponse4());
return View();
}
}
And these below ones are the methods that the async operations are running:
string GetReponse1() {
var req = (HttpWebRequest)WebRequest.Create("http://www.twitter.com");
req.Method = "HEAD";
var resp = (HttpWebResponse)req.GetResponse();
return FormatHeaders(resp.Headers);
}
string GetResponse2() {
var req2 = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com");
req2.Method = "HEAD";
var resp2 = (HttpWebResponse)req2.GetResponse();
return FormatHeaders(resp2.Headers);
}
string GetResponse3() {
var req = (HttpWebRequest)WebRequest.Create("http://google.com");
req.Method = "HEAD";
var resp = (HttpWebResponse)req.GetResponse();
return FormatHeaders(resp.Headers);
}
string GetResponse4() {
var req = (HttpWebRequest)WebRequest.Create("http://github.com");
req.Method = "HEAD";
var resp = (HttpWebResponse)req.GetResponse();
return FormatHeaders(resp.Headers);
}
private static string FormatHeaders(WebHeaderCollection headers) {
var headerStrings = from header in headers.Keys.Cast<string>()
select string.Format("{0}: {1}", header, headers[header]);
return string.Join("<br />", headerStrings.ToArray());
}
I have also Index2 method here which is synchronous and does the same thing.
I compare two operation execution times and there is major difference (approx. 2 seconds)
But I think I am missing lots of things here (exception handling, timeouts, etc). I only implement the exception handling on task3 but I don't think it is the right way of doing that.
What is the healthiest way of handling exceptions for this kind of operations?
Before accessing the result of a task you should test whether it completed successfully. If there was an error you should not try to access the results but instead do something with the exception:
task1.ContinueWith(t =>
{
if (!t.IsFaulted)
{
AsyncManager.Parameters["headers1"] = t.Result;
}
else if (t.IsFaulted && t.Exception != null)
{
AsyncManager.Parameters["error"] = t.Exception;
}
AsyncManager.OutstandingOperations.Decrement();
});