The operation has timed out in WCF REST Service - asp.net

I have created a web service using WCF REST Service Template 40(CS). When I try to consume it using
var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
if (method == "POST" && requestBody != null)
{
byte[] requestBodyBytes = ToByteArrayUsingJsonContractSer(requestBody);
request.ContentLength = requestBodyBytes.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
}
var response = request.GetResponse() as HttpWebResponse;
I keep getting:
The operation has timed out
How to increase time out ? Do I need to increase it in service or the client which is using this service with url:
http://myservice.com/RecordingCompleted/
Please suggest

try this code before Call the WEb Service.
request.Timeout = 5000;

Related

Forwarding SAML by delegation - POST from web server to web server

I have an ASP.NET web app using WSFederation for user authentication. I would like to impersonate the users and make a webrequest to another web server from my web server through delegation. The other server also does WSFederation.
Ultimately, i just need a single page from the other web server. There is some header info i need from that HTTP Response Header. Sample code below.
I have been following these steps but this is for Webserver -> WCF, not Webserver -> Webserver.
https://technet.microsoft.com/en-us/library/adfs2-identity-delegation-step-by-step-guide(v=ws.10).aspx
Based on that article, I got the following in my web.config:
<system.identityModel>
<identityConfiguration saveBootstrapContext="true">
Here is a bit of sample code that I'm running to make the web request to the second webapp. Its a simple POST and I need to read some data off the Response header.
try
{
var claimsPrincipal = ClaimsPrincipal.Current;
if (claimsPrincipal.Identities.First().BootstrapContext == null)
{
throw new Exception("No bootstrap context found");
}
WebRequest request = WebRequest.Create("https://destServer/sap/bc/gui/sap/its/webgui/?sap-client=555&sap-language=en");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseBody = new StreamReader(response.GetResponseStream()).ReadToEnd();
var responseHeaders = "";
for (int i = 0; i < response.Headers.Count; ++i)
{
responseHeaders += response.Headers.Keys[i] + ": " + response.Headers[i] + " <br/>";
}
ViewBag.responseHeader = responseHeaders;
ViewBag.responseBody = responseBody;
}
catch (Exception e)
{
ViewBag.responseHeader = "FAILED";
ViewBag.responseBody = e.Message;
}
I'm not sure how I need to add the appropriate SAML token into the request. Right now this results in a redirect response to the STS. I know I need to work with the STS admins to get the correct tokens, but assuming I already had this, how does one POST (or GET) to another website with those SAML tokens?

Getting Sharepoint-hosted app current user from within ASP.NET Web API

i have an ASP.NET Web API which i'm using in my SharePoint-hosted app to do CRUD operations via REST. I want to get the current user's credentials (O365 account) from within my web api controllers? Is it possible? Any suggestions or referenced would be much appreciated. TIA
I was able to accomplish this by using the below code in my controller:
Uri targetWeb = new Uri(HttpContext.Request.QueryString["SPHostUrl"]);
string targetRealm = TokenHelper.GetRealmFromTargetUrl(spContext.SPHostUrl);
var responseToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, targetWeb.Authority, targetRealm);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(spContext.SPHostUrl + "_api/Web/SiteUserInfoList/Items("+ spUser.Id + ")"); // spUser.Id from spContext
request.Method = "GET";
request.Accept = "application/json;odata=verbose";
request.ContentType = "application/json";
request.Headers.Add("Authorization", "Bearer " + spContext.UserAccessTokenForSPHost);
WebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
if (dataStream == null)
{
ViewBag.res = "nothing";
}else
{
StreamReader reader = new StreamReader(dataStream);
var result = reader.ReadToEnd();
var resData = Json(result);
ViewBag.res= resData.Data; // res must be parse when using js
}
return View();
...not sure if it's the best practice but it did the job.

can a MVC 3 app execute an Action in a different app on the same server

I have two asp.net applications running on one server, one is MVC-3, the other is not. the MVC application has a POST action which sends an email and returns a JSON object. Can the plain asp.net application somehow execute the action (from server) and receive the JSON object? I guess it just needs to execute a POST somehow?
Found the answer: It is the method HttpWebRequest, used as follows.
string data = "data to post";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("put URL here");
// set post headers
request.Method = "POST";
request.KeepAlive = true;
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
System.IO.StreamWriter writer = new System.IO.StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
writer.Dispose();
// next line posts the data to the URL
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

The remote server returned an error: (400) Bad Request while consuming a WCF Service

Please view the code given below. While the debug reaches the request.GetResponse() statement the error has been thrown.
Uri uri = new Uri(address);
string data = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><HasRole xmlns='http://tempuri.org/'><userName>" + sid + "</userName><role>" + role + "</role></HasRole></s:Body></s:Envelope>";
data.Replace("'", "\"");
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
if (uri.Scheme == Uri.UriSchemeHttps)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";// WebRequestMethods.Http.Post;
request.ContentLength = byteData.Length;
request.ContentType = "application/soap+xml; charset=UTF-8"; // "text/xml; charset=utf-8";
//request.ContentType = "application/x-www-form-urlencoded";
//Stream requestStream = request.GetRequestStream();
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteData, 0, byteData.Length);
}
//writer.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
Response.Close();
Response.Write(tmp);
}
I would double check the URL. If the URL looks ok on the client side, I recommend looking at access logs on your server to see what URL is being hit. 4xx errors mean a resource was not found. If the endpoint was correct, but the request was fubared, you would get a 5xx error code. (Assuming that your server side frameworks uses standard HTTP Response Codes).
As has been mentioned you should use the 'Add Service Reference' to access the WCF service from a .NET client. However, if you're emulating trying to connect from a non .NET client, your soap envelope is missing the header information.
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">
specify your action namespace here (e.g. http://tempuri.org/ISomeService/Execute)
</Action>
</s:Header>

How to send a xml file over HTTP and HTTPS protocol and get result back

i want to send xml file with userid and password over HTTPs and then send all other xml file on HTTP using POST method and get the response as a xml file back. in ASP.NET (with vb.net preferred)
The url to which i want to send my xml file is:http://www.hostelspoint.com/xml/xml.php
exect xml file pettern is:
<?xml version="1.0" encoding="UTF-8"?>
<OTA_PingRQ xmlns="http://www.opentravel.org/OTA/2003/05"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05OTA_PingRQ.xsd"
TimeStamp="2003-03-17T11:09:47-05:00"
Target="Production" Version="1.001" PrimaryLangID="en"
EchoToken="testtoken12">
<EchoData>Hello</EchoData>
</OTA_PingRQ>
You should check out the WCF REST Starter Kit, and watch the screencast on HTTP Plain XML (POX) Services which explains step by step how to do just that - create a WCF REST service that will accept and process a plain XML stream.
All the WCF and WCF REST screencasts by Pluralsight are highly recommended! It's excellent material on how to get started and work with WCF.
In addition to that, the MSDN WCF Developer Center is your first point of contact for any questions or more information on WCF and WCF REST.
i don't know why u removed correct answer from here but yesterday i got correct answer here. and it is:- (can any one tell me how to do same with HTTPS protocol?)
string targetUri = "http://www.hostelspoint.com/xml/xml.php";
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\myfile.xml"));
string formParameterName = "OTA_request";
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + 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();
}
}
Yes, you can do same thing using HTTPS protocol. You have to add this code before request:
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
bool validationResult = true;
//
// policy code here ...
//
return validationResult;
};

Resources