I have create a EndpointAddress like that
EndpointAddress address = new EndpointAddress("http://example.com/services/OrderService.svc");
But I could not add the Behavior to this Endpoint programmatically.
The behavior is given below.:
<behaviors>
<endpointBehaviors>
<behavior name="NewBehavior">
<dataContractSerializer maxItemsInObjectGraph="6553600" />
</behavior>
</endpointBehaviors>
</behaviors>
On the server you have to add it in the ServiceBehavior Attribute:
[ServiceBehavior(MaxItemsInObjectGraph = int.MaxValue)]
On the client you have to apply it to the endpoint. In this example you can see how to add it to all the endpoints in your ChannelFactory:
var factory = new ChannelFactory<IInterface>(...);
foreach (OperationDescription op in factory.Endpoint.Contract.Operations)
{
var dataContractBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>();
if (dataContractBehavior != null)
{
dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
}
}
On Server Sideļ¼ you can also:
ServiceHost host = new ServiceHost();
ServiceBehaviorAttribute sba = host .Description.Behaviors.Find<ServiceBehaviorAttribute>();
if (sba == null)
{
sba = new ServiceBehaviorAttribute();
sba.MaxItemsInObjectGraph = int.MaxValue;
host.Description.Behaviors.Add(sba);
}
Alternative: ((ServiceBehaviorAttribute) host.Description.Behaviors[typeof(ServiceBehaviorAttribute)]).MaxItemsInObjectGraph = int.MaxValue;
Related
I'm trying to connect my WCF service in Xamarine Forms, but in runtime I am getting this error
For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.
LoginWCFService.svc.cs
public class LoginWCFService : ILoginWCFService
{
public string LoginUserDetails(UserDetails userInfo)
{
string result = string.Empty;
bool res = false;
if (userInfo.uName!="" && userInfo.pWord != "" || userInfo.uName != null && userInfo.pWord != null)
{
result = "Login Successfull...";
}
else
{
res = false;
result = "Empty username or password";
}
return result.ToString();
}
}
ILoginWCFService.cs
[ServiceContract]
public interface ILoginWCFService
{
[OperationContract]
string LoginUserDetails(UserDetails UserInfo);
}
public class UserDetails
{
string UserName = string.Empty;
string Password = string.Empty;
[DataMember]
public string uName
{
get { return UserName; }
set { UserName = value; }
}
[DataMember]
public string pWord
{
get { return Password; }
set { Password = value; }
}
}
web.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ILoginWCFService" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://wcfapi.local/LoginWCFService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ILoginWCFService"
contract="WcfService_Omss.ILoginWCFService" name="BasicHttpBinding_ILoginWCFService" />
</client>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
Consuming WCF in Xamarine Form
LoginPage.xaml.cs
WCFServiceReference.LoginWCFServiceClient client = new LoginWCFServiceClient();
client.Open();
UserDetails user = new UserDetails();
user.uName = Uname.Text.ToString();
user.pWord = Pass.Text.ToString();
var res = client.LoginUserDetails(user); //Getting error here
if (res == "Login Successfull...")
await DisplayAlert("Message", "Login Successfull...", "Cancel");
else
await DisplayAlert("Message", "Login failed...", "Cancel");
client.Close();
Can anyone please tell me where I have to do changes to resolve this error?
This error has nothing to do with the wcf service. As the message says, set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings to the XmlReader.Create method. You can refer to the code below.
https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlreadersettings.dtdprocessing?view=net-6.0
using System;
using System.Xml;
using System.Xml.Schema;
using System.IO;
public class Sample {
public static void Main() {
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;
settings.ValidationType = ValidationType.DTD;
settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
// Create the XmlReader object.
XmlReader reader = XmlReader.Create("itemDTD.xml", settings);
// Parse the file.
while (reader.Read());
}
// Display any validation errors.
private static void ValidationCallBack(object sender, ValidationEventArgs e) {
Console.WriteLine("Validation Error: {0}", e.Message);
}
}
I have a created a WCF service which is consumed by android. It returns DataRows in json. As,
Web.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="httpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WcfAndroid.Service1">
<endpoint address=""
behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WcfAndroid.IService1" />
</service>
</services>
<protocolMapping>
<add binding="webHttpBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
Service Interface IService1 :
<OperationContract()> _
<WebInvoke(Method:="POST", UriTemplate:="GetEmp", ResponseFormat:=WebMessageFormat.Json)> _
Function GetEmp(ByVal EmpId As String) As DataTable
Service Class Service1 :
Public Function GetEmp(ByVal EmpId As String) As DataTable
Dim table As New DataTable("mytable")
table.Columns.Add("Result", GetType(String))
table.Columns.Add("acc", GetType(String))
table.Columns.Add("name", GetType(String))
table.Columns.Add("paid", GetType(Double))
'' Using EmpId for Fetching data from Database
table.Rows.Add("True", "1", "Employee1", 5000)
table.Rows.Add("True", "2", "Employee2", 2000)
Return table
End Function
EmpId is unique id for every employee. I am getting the details from Sql Server database. For testing i have sent 2 rows manually.
In android app for WebGet i have used :
public static JSONObject requestWebService(String serviceUrl) {
HttpURLConnection urlConnection = null;
try {
URL urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection)
urlToRequest.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
// handle unauthorized
} else if (statusCode != HttpURLConnection.HTTP_OK) {
// handle any other errors
}
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
String ss=getResponseText(in);
return new JSONObject(ss);
} catch (MalformedURLException e) {
// URL is invalid
} catch (SocketTimeoutException e) {
// data retrieval or connection timed out
} catch (IOException e) {
// could not read response body
// (could not create input stream)
} catch (JSONException e) {
// response body is no valid JSON string
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
But i don't know how to POST with EmpId and getDataRows.
I have to consume this service in android app. I am using HttpURLConnection.
How to post using HttpURLConnection and getDatarows (json format) ?
You can use OutputStreamWriter as :
public static JSONObject PostWebService(String serviceUrl) {
HttpURLConnection urlConnection = null;
try {
// create connection
URL urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection)
urlToRequest.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write("EmpID2016");
// You can write json also // Uncomment
// JSONObject jsonParam = new JSONObject();
// jsonParam.put("EmpID", "25");
// jsonParam.put("description", "Employer");
// jsonParam.put("authorized", "true");
// out.write(jsonParam.toString());
out.close();
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
// handle unauthorized (if service requires user login)
} else if (statusCode != HttpURLConnection.HTTP_OK) {
// handle any other errors, like 404, 500,..
}
// create JSON object from content
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
String ss=getResponseText(in);
return new JSONObject(ss);
} catch (MalformedURLException e) {
} catch (SocketTimeoutException e) {
} catch (IOException e) {
} catch (JSONException e) {
// response body is no valid JSON string
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
I'm wanting my web service to return JSON not XML, currently it's returning JSON wrapped in XML. View the source of my URL http://soulappvm.cloudapp.net/SAService/Service.svc/userlist produces the following...
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">[{"Name":"Daniel1user","Password":"40d5e24c5c906103a980ec7c69c100c5","Address":"123 st"},{"Name":"Daniel2user","Password":"90a1587cbe37d4a2a128ce758f338587","Address":"1234 st"},{"Name":"Daniel3user","Password":"f97c27c65d3af0d18657cbae16f9d57e","Address":"ccc"},{"Name":"user1user","Password":"def907bec025cd03bf738c3612bd7926","Address":"ds"},{"Name":"user2user","Password":"0fa04e1c4a5720195b106df9e746a72b","Address":"ff"}]</string>
Is there simple way to get it to just return JSON? I have tried ResponseFormat = WebMessageFormat.Json but that did not work.
IService
namespace SoulInfoService
{
[ServiceContract(SessionMode = SessionMode.Allowed, Namespace = "http://mmmkay95989.wix.com/bb2soulinfo")]
public interface IService
{
[OperationContract]
[WebGet(UriTemplate = "id")]
//[AspNetCacheProfile("CacheFor1200Seconds")]
string ServiceID();
[OperationContract]
[WebGet(UriTemplate = "version")]
//[AspNetCacheProfile("CacheFor1200Seconds")]
string Version();
[OperationContract]
[WebGet(UriTemplate = "userlist", ResponseFormat = WebMessageFormat.Json)]
[AspNetCacheProfile("CacheFor1200Seconds")]
string UserList();
[OperationContract]
[WebGet(UriTemplate = "usersearch?term={term}")]
User[] UserSearch(string term);
[OperationContract]
[WebGet(UriTemplate = "soulimg?id={id}")]
Stream SoulImage(string id);
[OperationContract]
[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
void GetOptions();
} // interface
}
Service
namespace SoulInfoService
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
public Service()
{
serviceID = Guid.NewGuid();
} // Service
public string ServiceID()
{
string rval = "";
rval = serviceID.ToString();
return rval;
} // ServiceID
public string Version()
{
return "1.0.0";
} // Version
public void GetOptions()
{
} // GetOptions
public string UserList()
{
User[] rval = null;
using (var sqlCommand = new SQLiteCommand("SELECT * FROM Users"))
{
rval = GetUsers(sqlCommand);
}
return JsonConvert.SerializeObject(rval);
//return rval;
} // UserList
public User[] UserSearch(string term)
{
User[] rval = null;
#if SANITY_CHECK
term = Sanitize(term);
#endif
string sqlString = String.Format("SELECT * FROM Users WHERE username LIKE '%{0}%'", term);
using (var sqlCommand = new SQLiteCommand(sqlString))
{
rval = GetUsers(sqlCommand);
}
for (int i = 0; i < rval.Length; i++)
{
System.Diagnostics.Debug.WriteLine("value: " + rval[i].Name);
}
return rval;
} // UserSearch
public Stream SoulImage(string id)
{
string categoryFolder = "/Souls/";
return GetImage(id, categoryFolder);
} //SoulImage
private Stream GetImage(string id, string categoryFolder)
{
string mimeType = "image/jpeg";
string fileExtension = "jpg";
ConfigReader config = new ConfigReader();
string dataRoot = config.GetString(CONFIG_DATA_ROOT, #"C:/");
string img = dataRoot + "/Images/" + categoryFolder + "/" + Path.ChangeExtension(id, fileExtension);
MemoryStream ms = null;
if (!File.Exists(img))
{
mimeType = "image/gif";
fileExtension = "gif";
img = dataRoot + "/Images/" + categoryFolder + "/" + Path.ChangeExtension(id, fileExtension);
if (!File.Exists(img))
{
mimeType = "image/png";
fileExtension = "png";
img = dataRoot + "/Images/" + categoryFolder + "/" + Path.ChangeExtension(id, fileExtension);
if (!File.Exists(img))
{
img = dataRoot + "/Images/Default.png";
}
}
}
ms = new MemoryStream(File.ReadAllBytes(img));
WebOperationContext.Current.OutgoingResponse.ContentType = mimeType;
return ms;
} // GetImage
private User[] GetUsers(SQLiteCommand command)
{
var list = new List<User>();
try
{
using (SQLiteConnection dbConnection = OpenDBConnection())
{
command.Connection = dbConnection;
using (SQLiteDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
var b = new User()
{
//Id = reader["TextId"].ToString(),
Name = reader["Username"].ToString(),
Password = reader["Password"].ToString(),
Address = reader["Address"].ToString(),
};
list.Add(b);
}
reader.Close();
}
dbConnection.Close();
}
}
catch (Exception ex)
{
string tmp = ex.Message;
}
return list.ToArray();
} // GetUsers
private static string Sanitize(string term)
{
Regex rgx = new Regex(#"[^\p{L}\p{N} ]+"); // \p{L} matches Unicode letters while \p{N} matches Unicode digits
term = rgx.Replace(term, ""); // Strip anything that isn't a letter or digit
return term;
} // Sanitize
private SQLiteConnection OpenDBConnection()
{
ConfigReader config = new ConfigReader();
string dataRoot = config.GetString(CONFIG_DATA_ROOT, #"C:/");
string dataDb = dataRoot + "/" + config.GetString(CONFIG_DATABASE, #"");
//string dataDb = dataRoot + "/" + databaseID;
string connectionString = String.Format("Data Source={0};Version=3;", dataDb);
SQLiteConnection dbConnection = new SQLiteConnection(connectionString);
dbConnection.Open();
return dbConnection;
} // OpenDBConnection
/// <summary>
/// Adds access control headers to service methods. One will need to add this when using
/// the Development Server which does not use system.webServer section of the Web.config
/// file and thus add the custom headers in there.
/// </summary>
private void AddAccessControlHeaders()
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Authorization, Content-Type");
} // AddAccessControlHeaders
private readonly string CONFIG_DATA_ROOT = "DataRoot";
private readonly string CONFIG_DATABASE = "Database";
private readonly string CONFIG_REALM = "Realm";
private readonly Guid serviceID;
} // class
}
Web.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="DataRoot" value="C:/Users/delm959/Documents/Database"/>
<add key="Database" value="TestDatabase.db"/>
<add key="Realm" value="Boutique Cassee"/>
</appSettings>
<!--
For a description of web.config changes for .NET 4.5 see http://go.microsoft.com/fwlink/?LinkId=235367.
The following attributes can be set on the <httpRuntime> tag.
<system.Web>
<httpRuntime targetFramework="4.5" />
</system.Web>
-->
<system.web>
<customErrors mode="Off"/>
<compilation debug="true" targetFramework="4.5"/>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="CacheFor1200Seconds" duration="1200" varyByParam="none" varyByHeader="Accept"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
<pages controlRenderingCompatibilityVersion="4.0"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="DefaultEndPointBehavior">
<dataContractSerializer maxItemsInObjectGraph="10000"/>
</behavior>
<behavior name="RESTEndPointBehavior">
<webHttp helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="WebHttpBindingConfig">
<!-- Comment out the security for HTTP; uncomment the security for HTTPS -->
<!--<security mode="Transport">
<transport clientCredentialType="None" />
</security>-->
</binding>
</webHttpBinding>
<basicHttpBinding>
<binding name="BasicHttpBindingConfig">
<readerQuotas/>
<!--
<security mode="None"/>
-->
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="SoulInfoService.Service">
<endpoint address="" behaviorConfiguration="RESTEndPointBehavior"
binding="webHttpBinding" bindingConfiguration="WebHttpBindingConfig"
bindingNamespace="http://www.example.org/Samples" contract="SoulInfoService.IService" />
<endpoint address="soap" behaviorConfiguration="DefaultEndPointBehavior"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBindingConfig"
bindingNamespace="http://www.example.org/Samples" contract="SoulInfoService.IService" />
<endpoint address="mex" binding="mexHttpBinding" bindingNamespace="http://www.example.org/Samples"
contract="IMetadataExchange" />
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Request-Method" value="OPTIONS, GET, POST"/>
<add name="Access-Control-Allow-Credentials" value="true"/>
<add name="Access-Control-Allow-Headers" value="Authorization, Content-Type"/>
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
This is a quite good tutorial how to create RESTful service with WCF which uses JSON formatter.
http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide
I have developed WCF RestFul service and created GET and POST methods.
and Hosted on internet server
Problem:
As for as my production machine every thing is fine, Get Method returns data;
POST method Inserts data to db.
But when i run on remote (internet) server) then GET methods are smooth
but POST method throws Exception with an inner Exception, here is Excepion
Main Exception: Unable to connect to the remote server
and Inner Exception: "No connection could be made because the target machine actively refused it 127.0.0.1:8888"
What should i do.
here is code (Client) Sample
Orders o = new Orders
{
OrderId = 1,
Dated = DateTime.Now.Date.ToString("dd/MM/yyyy"),
PartyCode = "1001",
PartyName = "Adnan Umar",
UserName="mau",
lstOrderDetail = new List<LineItem>()
{ new LineItem { SrNo = 1, ProductCode = "101", ProductName = "Mouse", Qty = 70, Discount = 0 },
new LineItem { SrNo = 2, ProductCode = "301", ProductName = "KeyBoard", Qty = 90, Discount = 0 } ,
new LineItem { SrNo = 3, ProductCode = "501", ProductName = "Mobile", Qty = 1980, Discount = 0 }
}
};
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Orders));
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, o);
string s = Encoding.UTF8.GetString(mem.ToArray());
WebClient webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
webClient.Encoding = Encoding.UTF8;
try
{
//webClient.UploadData("http://localhost:54144/RestServiceIMP.svc/SaveOrder","POST",mem.ToArray()); //working g8
webClient.UploadData("InternetAddress/restserviceimp.svc/SaveOrder", "POST", mem.ToArray());//not working
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}er
Here is SVC class
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "json/{id}")]
List<myProduct> JSONData(string id);
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "jsonParty/{id}")]
List<myParty> JSONPartyData(string id);
/*
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped , UriTemplate = "updateOrder")]
int UpdateOrderAddress(Stream JSONdataStream);
* */
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "SaveOrder")]
int SaveOrder(OrdersMain JSONdataStream);
and here is configuration file
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="RESTService.RestServiceIMP" behaviorConfiguration="ServiceBehaviour">
<endpoint address="" binding="webHttpBinding" contract="RESTService.IRestServiceIMP" behaviorConfiguration="web"></endpoint>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
I want to connect to a webservice url which is provided at runtime when user logs in. so i need to set Endpoint.Address in app.config at runtime.
EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
Uri uri = new Uri(txtURL.text.trim());
var address = new EndpointAddress(uri, spn);
var client = new EchoServiceClient("WSHttpBinding_IEchoService", address);
client.Close();
I placed this code on button click ,and gets the value of uri from textbox. Code is executing correctly and then getting an error message
"Address property on channelfactory.endpoint was null"
my app.config is:
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="LoginServiceSoap" />
</basicHttpBinding>
</bindings>
<client>
<!--<endpoint address="http://localhost:3073/LoginService.asmx" binding="basicHttpBinding"-->
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="LoginServiceSoap" contract="LoginService.LoginServiceSoap"
name="LoginServiceSoap" />
</client>
</system.serviceModel>
</configuration>
I've done something similar in a recent project, where I only wanted to set the endpoint and authentication programatically and not use the config file at all:
public static class ServiceClientFactory
{
public static HttpBindingBase BuildNavisionBinding(string endpointUrl)
{
//http://blog.randomdust.com/index.php/2010/10/could-not-establish-trust-relationship-for-the-ssl-tls-secure-channel/
//http://www.codeproject.com/Forums/1649/Csharp.aspx?fid=1649&df=90&mpp=25&sort=Position&select=3126652&tid=3121885
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate
{
return true;
});
if (endpointUrl.ToLower().StartsWith("https"))
{
var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
binding.MaxReceivedMessageSize = int.MaxValue - 1;
return binding;
}
else
{
var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
binding.MaxReceivedMessageSize = int.MaxValue - 1;
return binding;
}
}
public static TClient CreateClient<TClient, TChannel>(string endpoint, string username, string password)
where TClient : ClientBase<TChannel>
where TChannel : class
{
var client = (TClient)
Activator.CreateInstance(
typeof (TClient),
BuildNavisionBinding(endpoint),
new EndpointAddress(endpoint));
if (null == client.ClientCredentials)
throw new Exception(
string.Format("Error initializing [{0}] client. Client Credentials object was null",
typeof(TClient).Name));
client.ClientCredentials.Windows.ClientCredential =
new NetworkCredential(
username,
password);
client.ClientCredentials.Windows.AllowedImpersonationLevel =
TokenImpersonationLevel.Delegation;
client.Endpoint.Binding.SendTimeout = new TimeSpan(0, 0, 4, 0);
client.Endpoint.Binding.ReceiveTimeout = new TimeSpan(0, 4, 0);
client.Endpoint.Binding.OpenTimeout = new TimeSpan(0, 0, 4, 0);
return client;
}
So from your example:
var client = ServiceClientFactory.CreateClient<EchoServiceClient, IEchoServicePort(txtUrl.text.trim(), /* authentication */);