I'm actually new in C# and i'm currently building a simple basic Restful WCF webservice which using custom header authorization to proceed request
public void validateHeader(string requestBody)
{
try
{
IncomingWebRequestContext WebReq = WebOperationContext.Current.IncomingRequest;
string requestedURL = WebReq.UriTemplateMatch.RequestUri.OriginalString;
string clientHeader = WebReq.Headers["Authorization"];
if (clientHeader.Substring(0, 3) != "amx")
{
BuildUnauthorizedError("Unknown header");
}
Then i debugged it using Postman , with Authorization Header value added and it works as it should
But the problem is , when i try to debug the WCF using this console app :
try
{
string requestURL = "http://localhost:62146/ORIListenerService.svc/GetDataStatusPembayarans";
var request = (HttpWebRequest)WebRequest.Create(requestURL);
request.Method = "GET";
request.ContentType = "application/json";
request.PreAuthenticate = true;
request.Headers.Add("Authorization","amx 12345");
var response = (HttpWebResponse)request.GetResponse();
the Authorization header is not even received on the WCF
I also tried to fill the header value with random text , and its all received on WCF except the Authorization ..
Am i missing something or i just did it all wrong ?
Thanks in advance
Try adding "Accept" header parameter in request, thanks.
i found the solution, it turns out i missed the trailing / in my requestURL.
My UriTemplate in [OperationContract] is like this
UriTemplate = "/GetDataStatusPembayarans/"
but i call URL http://localhost:62146/GetDataStatusPembayarans
Related
I want to integrate bluesuit (https://docs.bluesuit.com/?shell#send-document) in C#. I want to upload a .pdf to bluesuit by setting Content-Type and Authorization Bearer using a WCF service. How to add this in header and call https://docs.bluesuit.com/?shell#send-document post method and get response and integrate bluesuit in C# with WCF?
Simply I just want to call a third party (bluesuit) post url in wcf service and get response from this third party (bluesuit) post url so how to call this third party post url in a WCF method?
Thanks in advance. need help please advice.
You can do it like this:
// Code to get a static WebClient
private static WebClient GetWebClient
{
get
{
var client = new WebClient
{
BaseAddress = "https://docs.bluesuit.com/?shell#send-document",
UseDefaultCredentials = true
};
client.QueryString.Clear();
client.Headers.Clear();
client.Headers.Add("content-type", "application/pdf");
return client;
}
}
Usage inside your function where you need to get response from bluesuit:
var client = GetWebClient;
// getToken() call returns you the Token as a string
client.Headers.Set(HttpRequestHeader.Authorization, "Bearer " + getToken());
var data = "Your data goes here";
var response = client.UploadString(url, "POST", data);
Process the response as per your use case.
I wrote a dll using HttpClient and tested it. It was working fine and then suddenly stopped working and instead of sending application/json started to send text/plain. In any case, I was advised to use HttpWebRequest instead of HttpClient. So I am trying to change my working code to that form. I also asked that question here https://social.msdn.microsoft.com/Forums/vstudio/en-US/e396d8ff-5260-42cd-aa5a-0a220d8bf123/switching-from-httpclient-to-webclient?forum=csharpgeneral
My problem is the following. I have host URL https://someSite.com and I also have two URLs which implement the API I need in the form of url = "/integrationapi//Attraction/Tickets/Validate"
I am not sure how should I create my request variable. I have a separate method which I call before attempting to get a response, e.g.
private void SetRequestHeaders(string tcHost, string tcUserName, string tcPassword, int tnTimeout)
{
request = WebRequest.Create(tcHost) as HttpWebRequest;
request.Host = tcHost;
request.Headers.Remove("Accept");
request.Headers.Add("Accept", "application/json");
string authorizationKey = Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", tcUserName, tcPassword)));
request.Headers.Add("Authorization", "Basic " + authorizationKey);
request.Timeout = tnTimeout * 1000;
}
Now, how should I use that request variable to call the API Url I need?
I have created a webhook
Order payment and given URL http://example.com/shopifydata.htm
Now I want to get all the data posted by shopify on order payment in C#
I have following code
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://example.com/shopifydata.htm");
myRequest.Method = "Get";
//if needs credential you can use myRequest.Credentials
using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
{
StreamReader mysr = new StreamReader(myResponse.GetResponseStream(), Encoding.GetEncoding("GB2312"));
//get the string content you can see what it is
string responseResult = mysr.ReadToEnd();
}
But I am not able to get anything
Where as when I use http://requestb.in/ I am able to get data. But can't get success on my site page
Please advise
Thanks
I'm new to JSON & am using VS 2013/C#. Here's the code for the request & response. Pretty straightforward, no?
Request request = new Request();
//request.hosts = ListOfURLs();
request.hosts = "www.cnn.com/www.cisco.com/www.microsoft.com/";
request.callback = "process";
request.key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string output = JsonConvert.SerializeObject(request);
//string test = "hosts=www.cnn.com/www.cisco.com/www.microsoft.com/&callback=process&key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
try
{
var httpWebRequest = (HttpWebRequest) WebRequest.Create("http://api.mywot.com/0.4/public_link_json2?);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = output;
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
MessageBox.Show(e.ToString());
}
//response = true.
//no response = false
return true;
}
When I run this, I get a 405 error indicating method not allowed.
It seems to me that there are at least two possible problems here: (1) The WoT API (www.mywot.com/wiki/API) requires a GET request w/ a body, & httpWebRequest doesn't allow a GET in the httpWebRequest.Method; or (2) the serialized string isn't serialized properly.
NOTE: In the following I've had to remove the leading "http://" since I don't have enough rep to post more than 2 links.
It should look like:
api.mywot.com/0.4/public_link_json2?hosts=www.cnn.com/www.cisco.com/www.microsoft.com/&callback=process&key=xxxxxxxxxxxxxx
but instead looks like:
api.mywot.com/0.4/public_link_json2?{"hosts":"www.cnn.com/www.cisco.com/www.microsoft.com/","callback":"process","key":"xxxxxxxxxxxxxxxxxxx"}.
If I browse to:api.mywot.com/0.4/public_link_json2?hosts=www.cnn.com/www.cisco.com/www.microsoft.com/&callback=process&key=xxxxxxxxxxxxxx; I get the expected response.
If I browse to: api.mywot.com/0.4/public_link_json2?{"hosts":"www.cnn.com/www.cisco.com/www.microsoft.com/","callback":"process","key":"xxxxxxxxxxxxxxxxxxx"}; I get a 403 denied error.
If I hardcode the request & send as a GET like below:
var httpWebRequest = (HttpWebRequest) WebRequest.Create("api.mywot.com/0.4/public_link_json2? + "test"); it also works as expected.
I'd appreciate any help w/ this & hope I've made the problem clear. Thx.
Looks to me like the problem is that you are sending JSON in the URL. According to the API doc that you referenced, the API is expecting regular URL encoded parameters (not JSON), and it will return JSON to you in the body of the response:
Requests
The API consists of a number of interfaces, all of which are called using normal HTTP GET requests to api.mywot.com and return a response in XML or JSON format if successful. HTTP status codes are used for returning error information and parameters are passed using standard URL conventions. The request format is as follows:
http://api.mywot.com/version/interface?param1=value1¶m2=value2
You should not be serializing your request; you should be deserializing the response. All of your tests above bear this out.
Users are authenticating to a REST WCF Service (my own). The credentials are sent through AJAX with Javascript and JSON format. The service reply with a OK and little info (redirect url) to the client, when authenticated.
Now, There are a new method provided for external authentication, and I have to create a compact code snippet that are easy to paste & run inside a asp.net code file method.
A typical wcf request could end up like this,
http://testuri.org/WebService/AuthenticationService.svc/ExtLogin?cId=197&aId=someName&password=!!pwd
My code snippet so far,
protected void bn_Click(object sender, EventArgs e)
{
WebHttpBinding webHttpBinding = new WebHttpBinding();
EndpointAddress endpointAddress = new EndpointAddress(url);
ContractDescription cd =
ContractDescription.GetContract(typeof(IAuthenticationService));
ServiceEndpoint sep = new ServiceEndpoint(cd);
sep.Behaviors.Add(new WebHttpBehavior());
sep.Address = endpointAddress;
sep.Binding = webHttpBinding;
var resp = new ChannelFactory<IAuthenticationService>(sepREST).CreateChannel();
LoginResult result = resp.ExtLogin(cId, aId, hashPwd);
Response.Redirect(result.RedirectUri);
// I.e. http://testuri.org/Profile.aspx (Require authenticated to visit)
}
I recieve correct authenticated reply in the resp/result objects. So, the communication are fine. When redirecting to the actual website, I'm not authenticated. I can't locate the problem? If I take the URI above (with valid credentials) and paste into my Webbrowser URL, and then manually type the uri, i'm authenticated.
I've spent a day searched the net for this, without success.
There are a LOT of info but none seem to apply.
What am I missing?
I also tried another approach but the same problem persist.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uriWithParameters);
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.ContentType = "application/json";
request.Accept = "application/json";
request.Method = "GET";
string result;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
result = reader.ReadToEnd();
JavaScriptSerializer jsonDeserializer = new JavaScriptSerializer();
LoginResult contact = jsonDeserializer.Deserialize<LoginResult>(result);
Response.Redirect(result.RedirectUri);
I'm not sure about this answer, but will offer it anyway as nobody else has posted:
I think it's because the request that has been authenticated is the request sent via code.
When you redirect it's a totally different request - so is still not authenticated.
All authentication techniques require some way of maintaining the authenticated state across 'stateless' requests = session cookies or some kind of authentication token.
Whatever token you get back from the call to the authentication service needs to be available to your website requests as well - dumping the token from the request into a cookie might be an option.
Can you see (in something like Fiddler) an auth token being sent as part of the request to 'RedirectUrl'?