Send web header collection - c#

How to send web header collection from rest Service to remoting service?
I have tried to send web headers using below code but its not working.
System.Net.WebRequest request = base.GetWebRequest(uri);
request.Headers.Add("myheader", "myheader_value");

You can try the below sample
public RemotingServiceClient serviceClient = new RemotingServiceClient();
public void Demo()
{
using (OperationContextScope scope = new OperationContextScope(serviceClient.InnerChannel))
{
MessageHeader<string> header = new MessageHeader<string>("HeaderValue1");
var v1 = header.GetUntypedHeader("HeaderName1", "RemotingService");
OperationContext.Current.OutgoingMessageHeaders.Add(v1);
header = new MessageHeader<string>("HeaderValue2");
var v2 = header.GetUntypedHeader("HeaderName2", "RemotingService");
OperationContext.Current.OutgoingMessageHeaders.Add(v2);
//IMP: To send headers make sure to call service in this block only.
//Keep unique uri name "RemotingService"
return serviceClient.MyRemotingServiceCall();
}
}
It's working for me as expected

Related

Setting proxy for Google Analytics Data API (GA4)

I need to config proxy credential for GA4 Client library to pass it from http proxy server, unfortunately there isn't any rich documentation for this purpose on the web (or maybe I couldn't find them)
Google Analytics Data API(GA4)
using Google.Analytics.Data.V1Beta;
using System.Net;
// Config Proxy Credential
WebProxy proxy = new WebProxy([proxy_url], [bypass]);
proxy.Credentials = new NetworkCredential([username], [password]);
// Google Analytics configuration
BetaAnalyticsDataClient client = BetaAnalyticsDataClient.Create();
RunReportRequest request = new RunReportRequest
{
Property = "properties/" + propertyId,
Dimensions = { new Dimension{ Name="city"}, },
Metrics = { new Metric{ Name="activeUsers"}, },
DateRanges = { new DateRange{ StartDate="2020-03-31", EndDate="today"}, },
};
// Make the request
var response = client.RunReport(request);
I have tried to assign object proxy to BetaAnalyticsDataClient or RunReportRequest object but I can't find it and I don't know how to use proxy configuration for GA4 library.

C# WCF Service Get Status Code in Client from One way Service

I have a WCF service which has a method named ArchiveFile(string fileName) which basically archives files. I have created a proxy project using svcutil and added its reference created in my client application and is consuming the service as follows:
var binding = new WSHttpBinding { Security = new WSHttpSecurity() { Mode = SecurityMode.None } };
var address = new EndpointAddress(this.TargetUrl);
var fileService = new FileServiceClient(binding, address);'
I want to know how do I determine the Http Status Code (200 - OK or any other) for the WCF Service call.
We can get the http status code through WebOperationContext Class:
WebOperationContext statuscode = WebOperationContext.Current;
Console.WriteLine(statuscode.OutgoingResponse.StatusCode);
For more information about WebOperationContext,please refer to the following link:
https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.web.weboperationcontext?view=netframework-4.8

C# AlphaVantage.NET: How-to use Proxy

I want to use this library AlphaVantage.NET.
I've tried the demo
string apiKey = "1"; // enter your API key here
var client = new AlphaVantageStocksClient(apiKey);
// retrieve daily time series for stocks of Apple Inc.:
StockTimeSeries timeSeries = await client.RequestDailyTimeSeriesAsync("AAPL", TimeSeriesSize.Compact, adjusted: false);
foreach (var dataPoint in timeSeries.DataPoints)
{
Console.WriteLine($"{dataPoint.Time}: {dataPoint.ClosingPrice}");
}
// retrieve stocks batch quotes for Apple Inc. and Facebook Inc.:
ICollection<StockQuote> batchQuotes = await client.RequestBatchQuotesAsync(new[] { "AAPL", "FB" });
foreach (var stockQuote in batchQuotes)
{
Console.WriteLine($"{stockQuote.Symbol}: {stockQuote.Price}");
}
But...is there any option to add a Proxy like in Using-WebClient? For example:
using (WebClient wc = new WebClient())
{
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
wc.Proxy = proxy;
var json = wc.DownloadString(#"https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY&symbol=BLDP&apikey=#############");
}
Sorry for my bad english :/
Unfortunately not.
Looking at the source of the library, there's no way of intercepting/injecting the underlying http client being used. The client is private to the library and being new'ed up as a static in the Core project here: https://github.com/LutsenkoKirill/AlphaVantage.Net/blob/master/AlphaVantage.Net/src/AlphaVantage.Net.Core/AlphaVantageCoreClient.cs#L24

c# webclient NetworkCredentials in Nodejs

I have a c# .net Client with this Code:
using(WebClient client = new WebClient())
{
string serialisedData = "";
serialisedData = JsonConvert.SerializeObject(myData);
client.Credentials = new NetworkCredential(config.UserData.Username, config.UserData.Password);
byte[] responsebyte = client.UploadData(config.ServerAddress, System.Text.Encoding.UTF8.GetBytes(serialisedData));
}
That Client sends data to my nodejs Server.
Nodejs Code:
var http = require('http');
var _server = http.createServer(_listener);
_server.listen(1234);
console.log( 'started' );
function _listener(req, res) {
let data = []
req.on('data', chunk => {
data.push(chunk)
})
req.on('end', () => {
data = Buffer.concat(data);
var dataString = new Buffer.from(data).toString("utf-8");
const data = JSON.parse(dataString);
// data has all the data from the c# object "myData"
res.write('response')
res.end()
})
}
But how can I access the credentials of this connection?
This is how I can Access the credentials in c#:
HttpListener listener = new HttpListener();
listener.Prefixes.Add($"https://+:{Config.Port}/");
listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
listener.Start();
for (; ; )
{
Console.WriteLine("Listening...");
IAsyncResult result = listener.BeginGetContext(new AsyncCallback(DoWork), listener);
result.AsyncWaitHandle.WaitOne();
result = null;
}
private void DoWork(IAsyncResult asyncResult)
{
HttpListener listener = (HttpListener)asyncResult.AsyncState;
HttpListenerContext context = listener.EndGetContext(asyncResult);
HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity;
// identity has the credentials
}
Edit: I cant change the c# Code anymore. So only nodejs solutions are needed
Edit2: The headers also have no Auth or Authentification property…
Edit3: I cant even find if other location exists except the header for credentials/authentification. But this must be possible right? I mean c# can somehow read this stuff from somewhere…
Any Idea what I can try to find the credentials?
To make your C# client to send its networkCredentials as HTTP Basic Authentication to your Nodejs server; the server should return a response whose header contains a HTTP 401 Unauthorized status and a WWW-Authenticate field if the request does not contain the Authorization header. This will cause your C# client retry the POST with Authorization header.
This process it is called Authentication challenge in case you want to search for more info.
There are serveral packages that does that for you; like http-auth or you can code it by hand (it is not very hard as it is just a matter of checking the existence of the Authorization header in the request and, if there is none or incorrect credentials, make a 401 response with a WWW-Authenticate field)
i.e. from the top of my head:
var http = require('http');
var _server = http.createServer(listener);
_server.listen(1234);
console.log('started');
function listener(req, res) {
if (!req.headers.authorization) {
res.statusCode = 401;
res.statusMessage = 'Unauthorized';
res.setHeader('WWW-Authenticate', 'Basic');
res.end();
}
}

Server Events Client - Getting rid of the automatically appended string at the end of the URI

I am new to the Service Stack library and trying to use the Server Events Client. The server I'm working with has two URIs. One for receiving a connection token and one for listening for search requests using the token acquired in the previous call.
I use a regular JsonServiceClient with digest authentication to get the token like so:
public const string Baseurl = "http://serverIp:port";
var client = new JsonServiceClient(Baseurl)
{
UserName = "user",
Password = "password",
AlwaysSendBasicAuthHeader = false
};
//ConnectionData has a string token property
var connectionData = client.Get<ConnectionData>("someServices/connectToSomeService");
And then use this token to listen for server events. Like so:
var eventClient =
new ServerEventsClient($"{Baseurl}/differentUri/retrieveSearchRequests?token={connectionData.Token}")
{
OnConnect = Console.WriteLine,
OnMessage = message => Console.WriteLine(message.Json),
OnCommand = message => Console.WriteLine(message.Json),
OnException = WriteLine,
ServiceClient = client, //same JsonServiceClient from the previous snippet
EventStreamRequestFilter = request =>
{
request.PreAuthenticate = true;
request.Credentials = new CredentialCache
{
{
new Uri(Baseurl), "Digest", new NetworkCredential("user", "password")
}
};
}
};
Console.WriteLine(eventClient.EventStreamUri); // "/event-stream&channels=" is appended at the end
eventClient.Start();
The problem with the above code is that it automatically appends "/event-stream&channels=" at the end of my URI. How do I disable this behavior?
I have tried adding the following class
public class AppHost : AppSelfHostBase
{
public static void Start()
{
new AppHost().Init().Start(Baseurl);
}
public AppHost() : base(typeof(AppHost).Name, typeof(AppHost).Assembly)
{
}
public override void Configure(Container container)
{
Plugins.Add(new ServerEventsFeature
{
StreamPath = string.Empty
});
Plugins.Add(new AuthFeature(() => new AuthUserSession(),
new IAuthProvider[]
{
new DigestAuthProvider()
}));
}
}
and called Start on it, before calling the above code, but still no luck.
The ServerEventsClient is only for listening to ServiceStack SSE Stream and should only be populated with the BaseUrl of the remote ServiceStack instance, i.e. not the path to the /event-stream or a queryString.
See this previous answer for additional customization available, e.g. you can use ResolveStreamUrl to add a QueryString to the EventStream URL it connects to:
var client = new ServerEventsClient(BaseUrl) {
ResolveStreamUrl = url => url.AddQueryParam("token", token)
});
If you've modified ServerEventsFeature.StreamPath to point to a different path, e.g:
Plugins.Add(new ServerEventsFeature
{
StreamPath = "/custom-event-stream"
});
You can change the ServerEventsClient to subscribe to the custom path with:
client.EventStreamPath = client.BaseUri.CombineWith("custom-event-stream");
ResolveStreamUrl + EventStreamPath is available from v5.0.3 that's now available on MyGet.

Categories

Resources