WCF service act as proxy for external web service - asp.net

I'm working on developing proxy WCF service. So tasks that I have to achieve as part of this assignment are:
I have to capture headers and content from an incoming request (from
a web browser).
Construct a web request for external web service with headers and
content from incoming request.
Execute web request.
Capture headers/cookies/content form the Response of external web
service.
Construct response, add headers/cookies and send response back to
browser.
I'm able to manage 1, 2 , 3 and 4 with help of web and stackoverflow. But not find any solution for task 5.
Questions:
Response message from external web service is a json. How to send the same message in json format to web browser?
Response from external web service has 'set-cookie' header. How to add this to web browser response?
I'm new to WCF and Web Service world. Using System.Net.Http.HttpClient to make a call to external web service. Open to change it to any other client library to achieve tasks 1 to 5.
Code blocks:
IService1.cs
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "client/api")]
string ProxyAPI(Stream inp);
Service1.cs
public string ProxyAPI(Stream contentStream)
{
// Task 1: Capture Headers and content
// Task 2: Construct web request with headers and content from incoming request
HttpClient proxyClient = new HttpClient();
Uri extWSuri = new Uri("http://router.sdc.com:8090/service/api");
proxyClient.BaseAddress = extWSuri;
// get input reqquest headers and add to httpclient onject
WebOperationContext current = WebOperationContext.Current;
WebHeaderCollection headers = current.IncomingRequest.Headers;
string[] headerKeys = headers.AllKeys;
foreach (string keyStr in headerKeys)
{
if (keyStr.ToLower().Equals("host"))
{
proxyClient.DefaultRequestHeaders.Add(keyStr, "router.simplifydc.com:8080");
}
else if (!keyStr.ToLower().StartsWith("cont"))
{
proxyClient.DefaultRequestHeaders.Add(keyStr, headers.GetValues(keyStr));
}
}
// get input content data
StreamReader reader = new StreamReader(contentStream);
string contentData = reader.ReadToEnd();
reader.Close();
// create content for httpclient request
StringContent contentRequest = new StringContent(contentData, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");
// Task 3: execute web request
Task<HttpResponseMessage> responseTask = proxyClient.PostAsync(extWSuri, contentRequest);
responseTask.Wait();
// Task 4: Capture headers/cookies/contnet from web response
HttpResponseMessage response = responseTask.Result;
HttpResponseHeaders resHeaders = response.Headers;
Task<string> contentTask = response.Content.ReadAsStringAsync();
contentTask.Wait();
string responseMsg = contentTask.Result;
// Task 5: construct response for incoming web browser request
// ?????????????
return responseMsg;
}

If I get it right, the client application for your WCF service is a web browser. This means that it expects an HTML document as a response right? In this case, I would suggest to avoid using a WCF service.
Why don't you use an ASP.NET page which forms the HTML to return? In your ASP.NET code behind, you could execute the 4 four steps you describe. In your 5th step, you would adjust the HTML to contain the data you got in the previous steps from the external web service.
You could always construct the HTML response using the WCF service, but I cannot see why. You could use and HTML DOM parser (like this to construct the HTML response programmatically, but this would not be my first approach.
If your page requires pure data and not HTML, your WCF service could return data in JSON format. As you can see, JSON is a simple string which could be very easy to construct. It depends on the data you want to return, but it could be very easy implemented either manually, or using some specific library like Json.NET. Then your UI application would parse JSON and display data accordingly.
Hope I helped!

Related

Using an asp web api in wpf

So i have got a simple question, when using our cms we can attach a driver as an executable.
The driver we want to make is an httpreceiver or just an api endpoint. SO i tought lets use asp.net web api for it -> using version .net 4.6.1. altough asp.net application requires a webserver and is not an executable, But i read on google you can use it inside a wpf application since our cms is wpf in the first place.
So my question is is there a way i can use my mvc web api project inside a wpf application? and if not what would be the best bet to have an httpreceiver or httppost receiver into an executable?
Main reason is we want to send httppost requests to the server as a desktop application. I know it's complicated but thats how it needs to be as far as I know.
In the case where asp is not an option, what the best way to make a postreqst/ httpreceiver as a desktop application?
EDit:
the resource guide from microsoft beneath was perfectly however i still have a question:
string baseAddress = "http://localhost:9000/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
// Create HttpClient and make a request to api/values
HttpClient client = new HttpClient();
string username = "test".ToUpper().Trim();
string password = "test123";
//Mock data
var body = new PostTemplate1();
body.Description = "test";
body.StateDesc = "httpdriver/username";
body.TimeStamp = DateTime.Now;
body.Message = "This is a post test";
var json = JsonConvert.SerializeObject(body);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var authToken = Encoding.ASCII.GetBytes($"{username}:{password}");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
var response = await client.PostAsync(baseAddress + #"api/Post", data);
var result = response.StatusCode;
}
As the guide says you post to url with port 9000
is there a possibility to use another port and use https?
if yes where to manage certificates for handling https?

Apache HTTP client 4.3 credentials per request

I have been having a look to a digest authentication example at:
http://hc.apache.org/httpcomponents-client-4.3.x/examples.html
In my scenario the there are several threads issuing HTTP requests and each of them has to be authenticated with their own set of credentials. Additionally, please consider this question is probably very specific for the Apache HTTP client 4.3 onwards, 4.2 handles authentication probably in a different way, although I didn't check it myself. That said, there goes the actual question.
I want to use just one client instance (static member of the class, that is threadsafe) and give it a connection manager to support several concurrent requests. The point is that each request will provide different credentials and I am not seeing the way to assign credentials per request as the credentials provider is set when building the http client. From the link above:
[...]
HttpHost targetHost = new HttpHost("localhost", 80, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
[...]
Checking:
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html#d5e600
The code sample in point 4.4 (seek 4.4. HTTP authentication and execution context), seems to say that the HttpClientContext is given the auth cache and the credentials provider and then is passed to the HTTP request. Next to it the request is executed and it seems that the client will get credentials filtering by the host in the HTTP request. In other words: if the context (or the cache) has valid credentials for the target host of the current HTTP request, he will use them. The problem for me is that different threads will perform different requests to the same host.
Is there any way to provide custom credentials per HTTP request?
Thanks in advance for your time! :)
The problem for me is that different threads will perform different requests to the same host.
Why should this be a problem? As long as you use a different HttpContext instance per thread, execution contexts of those threads are going to be completely indepenent
CloseableHttpClient httpclient = HttpClients.createDefault();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user:pass"));
HttpClientContext localContext = HttpClientContext.create();
localContext.setCredentialsProvider(credentialsProvider);
HttpGet httpget = new HttpGet("http://localhost/");
CloseableHttpResponse response = httpclient.execute(httpget, localContext);
try {
EntityUtils.consume(response.getEntity());
} finally {
response.close();
}
I have a similar issue.
I must call n-times a service with a single system user, authenticated with NTLM. I want to do this using multiple threads.
What I came up with is creating a single HTTPClient with no default credential provider. When a request needs to be performed I use an injected CredentialProviderFactory into the method performing the request (in a specific thread). Using this I get a brand new CredentialsProvider and I put this into a Context (created in the thread).
Then I call the execute method on the client using the overload execute(method, context).
class MilestoneBarClient implements IMilestoneBarClient {
private static final Logger log = LoggerFactory.getLogger(MilestoneBarClient.class);
private MilestoneBarBuilder builder;
private CloseableHttpClient httpclient;
private MilestoneBarUriBuilder uriBuilder;
private ICredentialsProviderFactory credsProviderFactory;
MilestoneBarClient(CloseableHttpClient client, ICredentialsProviderFactory credsProviderFactory, MilestoneBarUriBuilder uriBuilder) {
this(client, credsProviderFactory, uriBuilder, new MilestoneBarBuilder());
}
MilestoneBarClient(CloseableHttpClient client, ICredentialsProviderFactory credsProviderFactory, MilestoneBarUriBuilder uriBuilder, MilestoneBarBuilder milestoneBarBuilder) {
this.credsProviderFactory = credsProviderFactory;
this.uriBuilder = uriBuilder;
this.builder = milestoneBarBuilder;
this.httpclient = client;
}
// This method is called by multiple threads
#Override
public MilestoneBar get(String npdNumber) {
log.debug("Asking milestone bar info for {}", npdNumber);
try {
String url = uriBuilder.getPathFor(npdNumber);
log.debug("Building request for URL {}", url);
HttpClientContext localContext = HttpClientContext.create();
localContext.setCredentialsProvider(credsProviderFactory.create());
HttpGet httpGet = new HttpGet(url);
long start = System.currentTimeMillis();
try(CloseableHttpResponse resp = httpclient.execute(httpGet, localContext)){
[...]
For some reasons I sometimes get an error, but I guess it's an NTLMCredentials issue (not being thread-safe...).
In your case, you could probably pass the factory to the get methods instead of passing in creation.

Get HTTP Response from a url by using C#

Environment: ASP.Net MVC 4 using C#
I need to get image by using GET request to a URL /inbound/faxes/{id}/image
I used the code below
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("/inbound/faxes/238991717/image");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
System.IO.StreamReader stream = new StreamReader(response.GetResponseStream());
but it flags "URL not valid"
I used the complete URL www.interfax.net/inbound/faxes/{id}/image
but the result is same
I want to follow this article to receive faxes
Accepting incoming fax notifications by callback
Can anyone help me to get fax...?
Try like this:
using (var client = new WebClient())
{
byte[] imageData = client.DownloadData("http://www.interfax.net/inbound/faxes/{id}/image");
}
Notice how the url is prefixed with the protocol (HTTP in this case). Also make sure you have replaced the {id} part of the url with the actual id of the image you are trying to retrieve.

asp.net web api: accessing uploaded file stream

I have an asp.net web api application which is acting as a Relay to a wcf web service. In certain scenarios I want to upload large files. The methods in the wcf service accept files as stream.
I do not want to save the files on my intermediate server I want to access the stream of the uploaded file and provide it to the wcf method so that the data is directly streamed to the wcf service.
Here is similar scenario when client is downloading the file
using (IProductsChannel channel = ChannelFactory.CreateChannel())
{
result.Content = new StreamContent(channel.GetFile());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return result;
}
Here is at least one way of doing it. using the HTTPContext the only problem with this one is that it is not good for unit testing so we have to abstract it out in the final solution.
var file = HttpContext.Current.Request.Files[0];
var result = new HttpResponseMessage(HttpStatusCode.OK);
using (IProductsChannel channel = ChannelFactory.CreateChannel())
{
channel.SaveFile(file.InputStream);
}
return new HttpResponseMessage(HttpStatusCode.Created);
}

ASP.Net Web API - Authorization header blank

I am having to re-write an existing REST API using .NET (originally written with Ruby). From the client's perspective, it has to work exactly the same way as the old API - i.e. the client code mustn't need to change. The current API requires Basic Authentication. So to call the old API, the following works perfectly:-
var wc = new System.Net.WebClient();
var myCache = new CredentialCache();
myCache.Add(new Uri(url), "Basic", new NetworkCredential("XXX", "XXX"));
wc.Credentials = myCache;
var returnBytes = wc.DownloadData("http://xxxx");
(I have had to ommit the real URL / username / password etc for security reasons).
Now I am writing the new API using ASP.Net Web API with MVC4. I have a weird problem and cannot find anybody else with exactly the same problem. In order to support Basic Authentication, I have followed the guidelines here:
http://sixgun.wordpress.com/2012/02/29/asp-net-web-api-basic-authentication/
One thing, I put the code to "hook in the handler" in the Global.asax.cs file in the Application_Start() event (that wasn't explained so I guessed).
Anyway, if I call my API (which I have deployed in IIS) using the above code, the Authorization header is always null, and the above fails with 401 Unauthorized. However, if I manually set the header using this code, it works fine - i.e. the Authorization header now exists and I am able to Authenticate the user.
private void SetBasicAuthHeader(WebClient request, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
}
.......
var wc = new System.Net.WebClient();
SetBasicAuthHeader(request, "XXXX", "XXXX");
var returnBytes = wc.DownloadData("http://xxxx");
Although that works, it's no good to me because existing users of the existing API are not going to be manually setting the header.
Reading up on how Basic Authentication works, the initial request is meant to be anonymous, then the client is returned 401, then the client is meant to try again. However if I put a break point in my code, it will never hit the code again in Antony's example. I was expecting my breakpoint to be hit twice.
Any ideas how I can get this to work?
You're expecting the right behavior. System.Net.WebClient does not automatically include the Authorization headers upon initial request. It only sends them when properly challenged by a response, which to my knowledge is a 401 status code and a proper WWW-Authenticate header. See here and here for further info.
I'm assuming your basic authentication handler is not returning the WWW-Authenticate header and as such WebClient never even attempts to send the credentials on a second request. You should be able to watch this in Fiddler or a similar tool.
If your handler did something like this, you should witness the WebClient approach working:
//if is not authenticated or Authorization header is null
return base.SendAsync(request, cancellationToken).ContinueWith(task =>
{
var response = task.Result;
response.StatusCode = HttpStatusCode.Unauthorized;
response.Headers.Add("WWW-Authenticate", "Basic realm=\"www.whatever.com\"");
return response;
});
//else (is authenticated)
return base.SendAsync(request, cancellationToken);
As you noticed, if you include the Authorization headers on every request (like you did in your alternative approach) then your handler already works as is. So it may be sufficient - it just isn't for WebClient and other clients that operate in the same way.

Resources