hello i am working on asp.net and in that i want to add my contact list to constant contact website for that i have created trial account on constant contact. i used following code to add record to the constant contact database. but it show me following error
The remote server returned an error: (403) Forbidden.
i got exception on response part
Uri address=new Uri(sUri);
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Credentials=new NetworkCredential ((sAPIKey + "%" + sUsername), sPassword);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//Build data string
var data=new StringBuilder();
data.Append("activityType=" + HttpUtility.UrlEncode("ADD_CONTACTS", Encoding.UTF8));
data.Append("&data=" + HttpUtility.UrlEncode(("Email Address,Email Type,First Name,Last Name" + Convert.ToChar(10)), Encoding.UTF8));
data.Append(HttpUtility.UrlEncode((email.Text + ",HTML," + txtfname.Text + "," + txtlname.Text), Encoding.UTF8));
data.Append("&lists=" + HttpUtility.UrlEncode(sListUri));
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
string st = string.Empty;
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader reader = new StreamReader(response.GetResponseStream());
st = reader.ReadToEnd();
}
string sCode =Convert.ToString( Response.StatusCode);
thank you in advance.
If you open the page in firefox and inspect the response in firebug you will see the second part of the error number. 403 is just the first part. It might be 403.1 or 403.9 or whatever. there are lots and the specific one will help you narrow down the cause. Also, try the same in HTTPWatch.
Related
I have an ASP.NET web application in which I'm rendering different tableau dashboards from a site based on the menu clicked by the user. I have multiple menus and each menu was tied to a tableau URL.
Tableau Trusted Authentication has been implemented to get the trusted ticket from the tableau server. Once the ticket has been retrieved, I am appending the ticket to the dashboard URL along with the server name for each menu.
The trusted ticketing module is working fine and the visualizations are getting rendered in my web application. However, frequently I am getting a message of "Could not locate unexpired ticket" error.
On checking with this error, this is due to the ticket calls getting duplicated.
I reached out to the support regarding this and got a response that I can add client_ip during my trusted ticketing.
Tableau Trusted Ticket
I am not able to find any code article related to adding client_ip in trusted ticketing.
Below is my trusted ticket code.
public class TableauTicket
{
public string getTableauTicket(string tabserver, string sUsername)
{
try
{
ASCIIEncoding enc = new ASCIIEncoding();
string postData = string.Empty;
string resString = string.Empty;
postData = "username=" + sUsername + "";
// FEATURE 816 END - Custom Visualization - KV
if (postData != string.Empty)
{
byte[] data = enc.GetBytes(postData);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(tabserver + "/trusted");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
req.ContentLength = data.Length;
Stream outStream = req.GetRequestStream();
outStream.Write(data, 0, data.Length);
outStream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader inStream = new StreamReader(stream: res.GetResponseStream(), encoding: enc);
resString = inStream.ReadToEnd();
inStream.Close();
return resString;
}
else
{
resString = "User not authorised";
return resString;
}
}
catch (Exception ex)
{
string resString = "User not authorised";
return resString;
string strTrailDesc = "Exception in tableau ticket - " + ex.Message;
}
}
public int Double(int i)
{
return i * 2;
}
}
Can anyone please let me know how the client_ip can be passed in trusted ticketing code?
Also, the client IP will get changed for each user and how this will be handled in the trusted ticketing?
UPDATE
I have solved the issue using the source code provided by tableau on how to embed the view in SharePoint.
Below is the code which may help users having the same issue.
string GetTableauTicket(string tabserver, string tabuser, ref string errMsg)
{
ASCIIEncoding enc = new ASCIIEncoding();
// the client_ip parameter isn't necessary to send in the POST unless you have
// wgserver.extended_trusted_ip_checking enabled (it's disabled by default)
string postData = "username=" + tabuser + "&client_ip=" + Page.Request.UserHostAddress;
byte[] data = enc.GetBytes(postData);
try
{
string http = _tabssl ? "https://" : "http://";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(http + tabserver + "/trusted");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
// Write the request
Stream outStream = req.GetRequestStream();
outStream.Write(data, 0, data.Length);
outStream.Close();
// Do the request to get the response
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader inStream = new StreamReader(res.GetResponseStream(), enc);
string resString = inStream.ReadToEnd();
inStream.Close();
return resString;
}
// if anything bad happens, copy the error string out and return a "-1" to indicate failure
catch (Exception ex)
{
errMsg = ex.ToString();
return "-1";
}
}
Assuming your code is working, (I have done this part in Java and not really an expert in asp.net) all you have to do is to add something like:
postData = postData +"&client_ip=" +<variable for client IP>;
The way it is handled on tableau server is :
you turn on wgserver.extended_trusted_ip_checking on Tableau server. see details here
Tableau will match the client IP you passed in the POST request 'client_ip=XXX.XXX.XXX.XXX' while obtaining the token, with the actual IP of the the machine where the browser is trying to access tableau server.
I am learning Twilio Sending SMS tool. I created a trial account and have a verified phone number too.
I made post request to send sms through my aspx page but I got an authentication error.
Here is the code. Could anyone tell me what the problem is?
string url ="https://api.twilio.com/2010-04-01/Accounts/"+accontSid+ ":" + authenticationToken +"/SMS/Messages.json";
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
var authInfo = accSid + ":" + authToken;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Method = "POST";
var postData = "{\"To\":" +"\"" + ToNumber + "\"" + ", \"From\":" + "\"" + FromNumber + "\"" + ", \"Body\":" + "\"" + Body + "\"}";
var data = Encoding.UTF8.GetBytes(postData);
//request.ContentType = "application/json; charset=utf-8";
request.ContentType = "application/json";
request.ContentLength = data.Length;
Stream writer = null;
writer = request.GetRequestStream();
writer.Write(data, 0, data.Length);
writer.Close();
request.Headers["Authorization"] = "Basic"+authInfo;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string content = reader.ReadToEnd();
When I run this code, I get this error:
{"code": 20003, "detail": "Your AccountSid or AuthToken was incorrect.", "message": "Authentication Error - No credentials provided", "more_info": "https://www.twilio.com/docs/errors/20003", "status": 401}
What changes I should make?
Edit Change
try
{
string url ="https://api.twilio.com/2010-04-01/Accounts/"+accountSid+"/SMS/Messages.json";
string FromNumber = "+12012317746";
string ToNumber = "+91xxxxxxxxxx";
string Body = "Hello This is my test account.";
TwilioRestClient client = new TwilioRestClient(accSid, authToken);
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
var authInfo = accSid + ":" + authToken;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Method = "POST";
var postData = "{\"To\":" +"\"" + ToNumber + "\"" + ", \"From\":" + "\"" + FromNumber + "\"" + ", \"Body\":" + "\"" + Body + "\"}";
var data = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream writer = null;
writer = request.GetRequestStream();
writer.Write(data, 0, data.Length);
writer.Close();
request.Headers["Authorization"] = "Basic "+authInfo;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string content = reader.ReadToEnd();
client.SendMessage("+12012317746 ", txtToNo.Text, txtMsg.Text);
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Response.Write(reader.ReadToEnd());
}
}
I still get the same error.
Twilio developer evangelist here.
There is a couple of issues here. As CodeCaster pointed out, you do not need the Auth Token as part of the URL, just the Account SID.
Your Authorization header looks as though it is set up incorrectly, you don't have a space between "Basic" and the authInfo.
You have also set up the request type as "application/json". Twilio expects your POST request to have form encoded data as the body and the content type "application/x-www-form-urlencoded".
Twilio actually supply a C# helper library that you can use to make sending messages in Asp.net easier. You don't need to worry about the basic setup of the HTTP request and can just get on with building your application.
There are quite a few problems with this code. The error itself is already pretty clear; this request provides a response which you should read:
detail: Your AccountSid or AuthToken was incorrect.
message: Authentication Error - No credentials provided
more_info: https://www.twilio.com/docs/errors/20003
Read the errors, visit the mentioned "more info" page and read the documentation. The problems with your code:
You only have to provide the Account ID in the request URI, so lose the + ":" + authenticationToken.
You're not properly writing the basic authentication header. You're missing a space between "Basic" and the base64-encoded credentials.
Borrowed from the just-posted other answer: the content-type of the request also is incorrect.
As explained in the "more info" and documentation links above, use a client library. You don't want to reinvent the wheel.
Especially if you look at the last point, all of this code could be replaced with the following:
string AccountSid = "AC5ef872f6da5a21de157d80997a64bd33";
string AuthToken = "[AuthToken]";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var message = twilio.SendMessage(
"+14158141829", "+16518675309",
"Hey Jenny! Good luck on the bar exam!", ...);
I am consuming REST API (provided by client) in C#/asp.net and manipulate json result returned by that REST API. i have consume it by following code.
HttpWebResponse res = null;
string ReturnBody = string.Empty;
string requestBody = string.Empty;
WebRequest request = WebRequest.Create(Path);
request.ContentType = "application/json";
request.Method = "POST";
request.ContentLength = json.Length;
//Add Basic Auhtentication header
string authInfo = Username + ":" + Password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
sw.Write(json);
sw.Close();
res = (HttpWebResponse)request.GetResponse();
if (res != null)
{
using (StreamReader sr = new StreamReader(res.GetResponseStream(), true))
{
ReturnBody = sr.ReadToEnd();
StringBuilder s = new StringBuilder();
s.Append(ReturnBody);
sr.Close();
}
}
I have put above code in try catch block, so it works properly if it will return success code(200) so i can consume json response from res object as per above code
but when that REST API gives error then it will redirect to catch and res will be null so i can not access json response of error message as i can get it by Fiddler as per shown in below fig.
so help me about How can i consume that json error response through my code?
Thanks in Advance! for any help.
You will be probably getting WebException - inspect the status property. In your case, it will indicate protocol error i.e. 401/403 etc. In such case Response property can be use to get actual HTTP response. For example,
try
{
res = (HttpWebResponse)request.GetResponse();
// handle successful response
...
}
catch(WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
var response = (HttpWebResponse)ex.Response;
// use the response as needed - in your case response.StatusCode would be 403
// and body will have JSON describing the error.
..
}
else
{
// handle other errors, perhaps re-throw
throw;
}
}
I get an error when trying to retrieve word document by webservice
HttpWebRequest request;
Uri uri = new Uri(serverUrl +
"/bare.aspx/" + Request.PathInfo);
request = (HttpWebRequest)WebRequest.CreateDefault(uri);
request.KeepAlive = false;
request.AllowAutoRedirect = false;
request.ReadWriteTimeout = -1;
request.Timeout = -1;
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Method = "POST";
request.ContentType = "application/octet-stream";
// Serialize argument into request stream
Hashtable arguments = new Hashtable();
arguments["templateFile"] = templateFile;
arguments["hSetDataSource"] = hSetDataSource;
arguments["hSetRepeatBlock"] = hSetRepeatBlock;
arguments["messageForEmptyWord"] = messageForEmptyWord;
arguments["hImageBefore"] = hImageBefore;
arguments["hImageAfter"] = hImageAfter;
arguments["hImageInsideRepeater"] = hImageInsideRepeater;
MemoryStream buf = new MemoryStream();
BinaryFormatter fmt = new BinaryFormatter();
fmt.Serialize(buf, arguments);
request.ContentLength = buf.Length;
Stream reqStream = request.GetRequestStream();
buf.WriteTo(reqStream);
reqStream.Close();
buf.Close();
// Retreive word document from response and return it
// TODO: refactor this to stream directly into the response
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
When I check the webservice response (HttpWebResponse resp), I get the following error:
System.Net.WebException: The remote server returned an error: (404) Not Found.
I don't understand where is the problem, thank you in advance for your help.
You are not hitting the endpoint. A 404 means the server could not find the URL you are requesting. Verify your .asmx URL by putting it in your web browser. If that works then make sure you code is using that same URL.
I have got following code witch are sending xml file on HTTP protocol and getting response back as xml file from webserver and its working fine with HTTP protocol, but now i need to send such a XML file to HTTPS protocol (not http) and need to get response as xml file from it. the code to send xml file and get response from HTTP is :
string targetUri = "http://www.hostelspoint.com/xml/xml.php"; /*this will be like: "https://www.hostelspoint.com/xml/xml.php"*/
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\getdetail.xml"));
string formParameterName = "OTA_request";
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
//string sendString = HttpUtility.UrlEncode(xmlData);
byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
string respStr = "";
if (request.HaveResponse)
{
if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
{
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respStr = respReader.ReadToEnd(); // get the xml result in the string object
XmlDocument doc = new XmlDocument();
doc.LoadXml(respStr);
Label1.Text = doc.InnerXml.ToString();
}
}
There shouldn't be much difference in your code, as HTTP or HTTPS differs only in transport level, not in application level.
What may become a problem here is, if the server certificate used in the targetUri is trusted on your server. In this case the HTTPS identity cannot be verified.