I'm having problems calling a method in a WCF service from classic ASP. Below is the code for the service and the configuration:
Service
[ServiceContract(Namespace = "http://Plumtree.dartKW.PdfGenerator.Web")]
public interface IPdfGeneratorService
{
[OperationContract]
String GeneratePdf(String xml);
}
public class PdfGeneratorService : IPdfGeneratorService
{
#region IPdfGeneratorService Members
public String GeneratePdf(String xml)
{
return "hello";
}
#endregion
}
Configuration
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_PdfGenerator"
maxBufferSize="2147483647"
maxReceivedMessageSize="2147483647"
maxBufferPoolSize="2147483647"
transferMode="Buffered">
<readerQuotas
maxArrayLength="2147483647"
maxStringContentLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647"
maxDepth="32" />
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="serviceBehavior"
name="Plumtree.dartKW.PdfGenerator.Web.PdfGeneratorService">
<endpoint binding="basicHttpBinding"
bindingName="BasicHttpBinding_PdfGenerator"
contract="Plumtree.dartKW.PdfGenerator.Web.IPdfGeneratorService" />
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
I have tested the above method in the WCF Test Client and it works fine. Here is the code from my asp page:
mexMonikerString = "service:mexAddress='http://localhost:51997/PdfGeneratorService.svc/mex'"
mexMonikerString = mexMonikerString + ", address='http://localhost:51997/PdfGeneratorService.svc'"
mexMonikerString = mexMonikerString + ", binding=basicHttpBinding"
mexMonikerString = mexMonikerString + ", bindingNamespace='http://tempuri.org/'"
mexMonikerString = mexMonikerString + ", contract=IPdfGeneratorService"
mexMonikerString = mexMonikerString + ", contractNamespace='http://Plumtree.dartKW.PdfGenerator.Web'"
dim service
service = GetObject(mexMonikerString)
Whenever I try this I get the following error:
System.ServiceModel error '800401e4'
The contract does not have an endpoint supporting the binding specified.
I've tried passing the binding configuration name BasicHttpBinding_PdfGenerator in the moniker instead of basicHttpBinding but I get the same error. I can't find any other examples of this error online either.
Any help would be greatly appreciated
You can do it using JavaScript without too much difficulty. Here's a copy of some JavaScript embedded in a simple HTML page that I give to my would-be WCF web service users.
The hard part might be figuring out what the WCF service expects in the request. If you have access to the WCF service code it's pretty easy to figure out. Another way would be to use Fiddler to capture successful messages sent between a client and wcf host. Or the WSDL, if you can generate one.
Good luck.
function Ping() {
//set up varable
var sContent;
// 'Content-Type: text/xml \r\n ' +
// 'Host: localhost:8085 \r\n \r\n ';
sContent= "<xml>Your message matching the web service's data or message contract</xml>";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', Demo.URL.value, true);
xmlhttp.onreadystatechange = function() {
//this section acts as a listener, waiting for response from host
if (xmlhttp.readyState == 4||xmlhttp.readyState == 0) {
//alert("Ready state: " + xmlhttp.readyState.toString());
if (xmlhttp.status == 200) {
//alert("good");
Demo.pingresponse.value = "Response: " +xmlhttp.responseText;
}
if (xmlhttp.status !=200){
//alert("bad");
Demo.pingresponse.value = "Error: " +xmlhttp.status.toString() +" response text: " +xmlhttp.responseText;
}
} else {
//alert("readystate bad");
}
}
//send request
xmlhttp.setRequestHeader("POST http:localhost:8085/HostInterface/HostConnect HTTP/1.1");
xmlhttp.setRequestHeader("VsDebuggerCausalityData","");
xmlhttp.setRequestHeader ("SOAPAction","\"http://somestuff\"");
xmlhttp.setRequestHeader("Host","localhost:8085");
xmlhttp.setRequestHeader("Expect","100-continue");
xmlhttp.setRequestHeader("Accept-Encoding","gzip, deflate");
xmlhttp.setRequestHeader("Connection","Keep-Alive");
xmlhttp.setRequestHeader("Content-Length","639");
xmlhttp.setRequestHeader("Content-type", "text/xml; charset=utf-8");
xmlhttp.send(sContent);
}
Related
I have a problem with metadata (wsdl on service soap).
Locally everything works fine. and at the address https: // localhost / DataImportSoapService /? wsdl the wsdl is exposed.
Nothing is shown on the server. Return 404.
I state that I have other active services in WCF and that the other .svc are correctly exposed.
While this basicHttpBinding service with basic auth doesn't work.
So on the server I activated everything:
My web.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DatineoUser" value="zzzzzz" />
<add key="DatineoPass" value="xxxx" />
<add key="UrlServiceNewEra" value="https://xxxxx/common/importDataCarrier?satcode=datineo" />
</appSettings>
<system.web>
<compilation debug="true" />
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<services>
<service behaviorConfiguration="MetadataBehavior" name="TA_service_library_BA.DataImportSoapService">
<endpoint address="datineoV1" binding="basicHttpBinding"
bindingConfiguration="wsHttpBinding_LargeBinding" name="EndpointAVeryBigSum_BasicAuthentication"
contract="TA_service_library_BA.IDataImportSoapService" />
<endpoint address="mex"
binding="mexHttpsBinding"
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="https://localhost/DataImportSoapService/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MetadataBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="TA_service_library_BA.ServiceAuthenticator, TA_service_library_BA"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="wsHttpBinding_LargeBinding" closeTimeout="00:05:00" openTimeout="00:05:00" receiveTimeout="00:15:00" sendTimeout="00:15:00" maxBufferSize="15728640" maxBufferPoolSize="15728640" maxReceivedMessageSize="15728640">
<readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
</configuration>
My classes:
namespace TA_service_library_BA
{
public class ServiceAuthenticator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
throw new SecurityTokenException("Username and password required");
if (!(userName == ConfigurationManager.AppSettings["DatineoUser"] && password == ConfigurationManager.AppSettings["DatineoPass"]))
throw new FaultException(string.Format("Wrong username ({0}) or password ", userName));
}
}
}
namespace TA_service_library_BA
{
// NOTA: è possibile utilizzare il comando "Rinomina" del menu "Refactoring" per modificare il nome di interfaccia "IDataImportService" nel codice e nel file di configurazione contemporaneamente.
[ServiceContract(Namespace = "http://sen.company.com")]
[XmlSerializerFormat]
public interface IDataImportSoapService
{
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
PushResponse PushDataArray(PushData pushDataArray);
//++++++++++++++++++++++++++++++++++++++++++++++
}
}
namespace TA_service_library_BA
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
public class DataImportSoapService : IDataImportSoapService
{
public PushResponse PushDataArray(PushData pushDataArray)
{
PushResponse responsePush = new PushResponse();
try
{
string authkey = ConfigurationManager.AppSettings["DatineoUser"] + ":" + ConfigurationManager.AppSettings["DatineoPass"];
string encAuthkey = CommFun.Base64Encode(authkey);
WebRequest request = WebRequest.Create(ConfigurationManager.AppSettings["UrlServiceNewEra"]);
request.ContentType = "application/json";
request.Method = "POST";
request.Headers.Add("Authorization", "Basic " + encAuthkey);
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(pushDataArray);
streamWriter.Write(json);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
if (response.StatusCode.Equals(HttpStatusCode.OK) || response.StatusCode.Equals(HttpStatusCode.NoContent))
{
//istanzio la risposta contenitore
responsePush.success = true;
responsePush.message = responseString;
}
else
{
//istanzio la risposta contenitore
responsePush.success = false;
responsePush.message = responseString;
}
}
catch (Exception ex)
{
//istanzio la risposta contenitore
responsePush.success = false;
responsePush.message = ex.Message;
}
return responsePush;
}
}
}
Why do some projects expose at least the .svc while this last service gives me 404 to the .svc file?
Beyond this then I don't understand what the hell is wrong with the configuration ... with IIS express everything goes .. on the server no.
Thanks for your help. I've been banging my head for a week and a half. I have tried the impossible. Tnx
You can check the following conditions:
Whether the permission of the managed directory is granted.
Whether the.NET version matches.
Is there a valid certificate on the site.
Try to put the image in the same path and find it.
I've created a WCF service to receive data from a sending application. When run, the usual index listing appears:
and clicking on the .svc shows the success page:
So, I've created a basic test form to invoke the methods of the service (there are 2, both are "POST" methods). Since the service methods use JSON & webhttp, I am attempting to invoke the service via an HttpWebRequest.
private void button1_Click(object sender, EventArgs e) {
try {
var request = (HttpWebRequest)WebRequest.Create("http://localhost:54945/Take2ToOffice.svc/ErrorReport");
request.ContentType = "'text/json; charset=utf-8'";
request.Method = "POST";
byte[] chunk = new byte[2048]; //chunk gets initialised, but what it
//contains is mostly irrelevant here
string result = "";
ErrorInfo EI = new ErrorInfo {
Edumis = "9999",
SiteName = "Unknown",
ErrorID = "123",
ContentBlock = chunk
};
string json = new JavaScriptSerializer().Serialize(EI);
//MessageBox.Show(json);
using (var sW = new StreamWriter(request.GetRequestStream())) {
sW.Write(json);
sW.Flush();
sW.Close();
}
var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream())) {
result = streamReader.ReadToEnd();
}
MessageBox.Show(result);
}
catch (WebException wex) {
string lcResult;
if (wex.Response != null) {
lcResult = "ERROR (web exception, response generated): " + Environment.NewLine;
StreamReader sr = new StreamReader(wex.Response.GetResponseStream());
lcResult += sr.ReadToEnd();
}
else {
lcResult = "ERROR (web exception, NO RESPONSE): " + wex.Message + wex.StackTrace;
}
MessageBox.Show(lcResult);
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
It all seems like pretty basic stuff - especially since I wrote another service very similar to this a few years ago, and my starting point for everything I've done now, was the code I wrote previously - and at this point, I'm just doing this in my development environment.
Yet,
var response = (HttpWebResponse)request.GetResponse();
Returns 404 Not Found. The WebException.Response contains:
{System.Net.HttpWebResponse}
[System.Net.HttpWebResponse]: {System.Net.HttpWebResponse}
base: {System.Net.HttpWebResponse}
ContentLength: 0
ContentType: ""
Headers: {X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcVXNlclxEb2N1bWVudHNcVmlzdWFsIFN0dWRpb1xWaXN1YWwgU3R1ZGlvIDIwMTNcUHJvamVjdHNcVGFrZTJPZmZpY2VDb21tdW5pY2F0aW9uc1xUYWtlMk9mZmljZUNvbW11bmljYXRpb25zXFRha2UyVG9PZmZpY2Uuc3ZjXEVycm9yUmVwb3J0?=
Content-Length: 0
Cache-Control: private
Date: Thu, 27 Apr 2017 03:19:29 GMT
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
}
IsFromCache: false
IsMutuallyAuthenticated: false
ResponseUri: {http://localhost:54945/Take2ToOffice.svc/ErrorReport}
SupportsHeaders: true
But there is no actual response at all (length = 0). If I put a breakpoint in the service, (and start both the test form, and the service - separate projects in the same solution), the breakpoint is never hit.
Logically it looks like the service isn't running, or for some reason can't be found - but the listing and success page are readily seen in a browser, and at the address (localhost:54945) shown in the program.
Can anyone explain what's going on, or maybe what's going wrong? Please help, I'm totally stumped.
The web.config is as follows:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
...
</connectionStrings>
<appSettings>
...
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime/>
</system.web>
<system.serviceModel>
<services>
<service name="Take2OfficeCommunications.Take2ToOffice" behaviorConfiguration="serviceBehavior">
<endpoint address="rest"
binding="webHttpBinding"
bindingConfiguration="WebBinding"
behaviorConfiguration="web"
name="restEndpoint"
contract="Take2OfficeCommunications.ITake2ToOffice"/>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="WebBinding" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
<security mode="Transport" />
<readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="serviceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
Thanks for looking, and for any comments you can make.
I made wcf rest service by going New->projects->WCF Service Application
I am unable to use methods in console application while i have hosted wcf rest service and referenced wcf rest service in application
My Application code is below :
IRestServiceImpL
[ServiceContract]
public interface IRestServiceImpL
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml,
RequestFormat = WebMessageFormat.Xml, UriTemplate = "XmlData/{id}")]
string XmlData(string id);
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json, UriTemplate = "JsonData/{id}")]
string JsonData(string id);
}
RestServiceImpL.svc.cs
[AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Allowed)]
public class RestServiceImpL : IRestServiceImpL
{
public string XmlData(string id)
{
return "you requested for " + id;
}
public string JsonData(string id)
{
return "you requested for " + id;
}
}
Config File
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="StreamedRequestWebBinding"
bypassProxyOnLocal="true"
useDefaultWebProxy="false"
hostNameComparisonMode="WeakWildcard"
sendTimeout="10:15:00"
openTimeout="10:15:00"
receiveTimeout="10:15:00"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
transferMode="StreamedRequest"
crossDomainScriptAccessEnabled="true"
>
<readerQuotas maxArrayLength="2147483647"
maxStringContentLength="2147483647" />
</binding>
</webHttpBinding>
</bindings>
<services>
<service name="RestService.RestServiceImpL" behaviorConfiguration="ServiceBehaviour">
<!--<endpoint address="" binding="basicHttpBinding" contract="RestService.IRestServiceImpL"></endpoint>-->
<endpoint address="" binding="webHttpBinding" name="StreamedRequestWebBinding" bindingConfiguration="StreamedRequestWebBinding" contract="RestService.IRestServiceImpL" behaviorConfiguration="web"></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" aspNetCompatibilityEnabled="true" />
</system.serviceModel>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
I host this service application in IIS
Now after giving reference to console application when i call its methods
by using proxy class then i got error of Invalid Operation Contract Exception
that endpoint not specified
calling code is below :
ServiceClient oServiceClient = new ServiceClient();<br/>
oServiceClient.JsonData("123");
Please suggest what is problem in the code.
Thanks stack overflow for support...I did it..
The calling Wcf Rest Service code is written below :
//code for xml Response consumption from WCF rest Service[Start]
WebRequest req = WebRequest.Create(#"http://RestService.com/WcfRestService/RestServiceImpL.svc/XmlData/sad");
req.Method = "GET";
req.ContentType = #"application/xml; charset=utf-8";
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
if (resp.StatusCode == HttpStatusCode.OK)
{
XmlDocument myXMLDocument = new XmlDocument();
XmlReader myXMLReader = new XmlTextReader(resp.GetResponseStream());
myXMLDocument.Load(myXMLReader);
Console.WriteLine(myXMLDocument.InnerText);
}
//code for xml Response consumption from WCF rest Service[END]
//****************************************************************************
//code for json Response consumption from WCF rest Service[Start]
WebRequest req2 = WebRequest.Create(#"http://RestService.com/WcfRestService/RestServiceImpL.svc/JsonData/as");
req2.Method = "GET";
req2.ContentType = #"application/json; charset=utf-8";
HttpWebResponse response = (HttpWebResponse)req2.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
jsonResponse = sr.ReadToEnd();
Console.WriteLine(jsonResponse);
}
//code for json Response consumption from WCF rest Service[END]
I've read a lot of posts about the problem to use WP7 + WCF (IIS 7) over HTTPS with basic authentication but I'm still in trouble with it...
If I just use HTTPS transport without BasicAuth it works like a charm. But both combinated doesn't work for me...
Maybe you can help me to identify my failure...
My ClientConfig:
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" maxBufferSize="2147483647"
maxReceivedMessageSize="2147483647">
<security mode="Transport" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"
contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />
</client>
</system.serviceModel>
My ServiceConfig:
<?xml version="1.0"?>
<configuration>
<appSettings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WP7.CustomUserNameValidator, WP7" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<bindings>
<basicHttpBinding>
<binding maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="TransportWithMessageCredential" >
<transport clientCredentialType="Basic"/>
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
My CustomUserNameValidator used in Service:
namespace WP7
{
public class CustomUserNameValidator : UserNamePasswordValidator
{
// This method validates users. It allows in two users,
// test1 and test2 with passwords 1tset and 2tset respectively.
// This code is for illustration purposes only and
// MUST NOT be used in a production environment because it
// is NOT secure.
public override void Validate(string userName, string password)
{
if (null == userName || null == password)
{
throw new ArgumentNullException();
}
if (!(userName == "test1" && password == "1tset") && !(userName == "test2" && password == "2tset"))
{
throw new FaultException("Unknown Username or Incorrect Password");
}
}
}
}
The code in my Wp7 App to call a method a sync (with a solution from: http://cisforcoder.wordpress.com/2010/12/01/how-to-implement-basic-http-authentication-in-wcf-on-windows-phone-7/#comment-174):
proxy = new ServiceReference1.Service1Client();
proxy.Endpoint.Address = new System.ServiceModel.EndpointAddress(new Uri(Details.mySettings.EndpointAddress));
proxy.PingServerCompleted += new EventHandler<ServiceReference1.PingServerCompletedEventArgs>(proxy_PingServerCompleted);
var credentials = EncodeBasicAuthenticationCredentials("test1", "1tset");
using (OperationContextScope scope =
new OperationContextScope(proxy.InnerChannel))
{
HttpRequestMessageProperty request = new HttpRequestMessageProperty();
request.Headers[System.Net.HttpRequestHeader.Authorization] = "Basic " + credentials;
OperationContext.Current.OutgoingMessageProperties.Add(
HttpRequestMessageProperty.Name, request);
proxy.PingServerAsync(myServer);
}
private string EncodeBasicAuthenticationCredentials(string username, string password)
{
//first concatenate the user name and password, separated with :
string credentials = username + ":" + password;
//Http uses ascii character encoding, WP7 doesn’t include
// support for ascii encoding but it is easy enough to convert
// since the first 128 characters of unicode are equivalent to ascii.
// Any characters over 128 can’t be expressed in ascii so are replaced
// by ?
var asciiCredentials = (from c in credentials
select c <= 0x7f ? (byte)c : (byte)'?').ToArray();
//finally Base64 encode the result
return Convert.ToBase64String(asciiCredentials);
}
Furthermore I've already set "Basic Authentication" setting in the IIS Virtual Directory to "Enabled".
Everytime I've got some different error exceptions:
either CommunicationException or SecurityException or what else...
Someone an idea which might be solve my problem?
Thanks.
Jason
The client needs to also specify the clientCredentialType - that's missing from the client config. So the client isn't expecting to have to send credentials but the service is expecting them
I have a requirement of creating a webservice where the client and the service will talk in Simple Soap (that request and response will be soap), I tried all to find a sample example on net where this thing is already done or some code sample so that I can get started but I think I am bad in searching google, that is why can't find any one so far, Some one suggested to use WCF so get an article
http://csharping.com/wcf/building-a-soap-response-envelope-manually-with-the-message-class/
But again my problem is not solved, I tried to create an application with this sample (with so many issues :( )
Created a console application and the Program.cs is
using System;
using System.IO;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Text;
using System.Runtime.Serialization;
namespace ServiceConsole
{
public class Program
{
static void Main(string[] args)
{
using (ServiceHost serviceHost = new ServiceHost(typeof(ServiceClient), new Uri("http://localhost:2000/")))
{
ServiceEndpoint serviceEndpoint = new ServiceEndpoint(
ContractDescription.GetContract(typeof(IService)));
ServiceEndpoint metadataEndpoint = new ServiceEndpoint(
ContractDescription.GetContract(typeof(IMetadataExchange)));
ServiceMetadataBehavior metadataBehavior = serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (metadataBehavior == null)
{
metadataBehavior = new ServiceMetadataBehavior();
metadataBehavior.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(metadataBehavior);
}
serviceHost.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "http://localhost:2000/");
serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "http://localhost:2000/WCFService/mex");
serviceHost.Open();
string requestData = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Header><h:HeaderItem xmlns:h=\"http://tempuri.org/\">a header item</h:HeaderItem><ActivityId CorrelationId=\"090c553b-bfcc-4e4f-94cd-1b4333fe82a9\" xmlns=\"http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics\">377a454b-b543-4c6f-b4ac-3981029b60e6</ActivityId></s:Header><s:Body><string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">a body item</string></s:Body></s:Envelope>";
byte[] requestDataBytes = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/WCFService/");
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";
request.Headers.Add("SOAPAction", "http://tempuri.org/IWebService/GetMessage");
request.ContentLength = requestDataBytes.Length;
StreamWriter streamWriter = new StreamWriter(request.GetRequestStream());
streamWriter.Write(requestData);
streamWriter.Flush();
streamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
string responseBody = streamReader.ReadToEnd();
Console.WriteLine("Service returned the following response...");
Console.WriteLine("");
Console.WriteLine(responseBody);
Console.ReadKey();
serviceHost.Close();
}
}
}
}
the app.config which I generated using svcutil.exe is like this
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:2000/WebService/Service.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService"
contract="IService" name="BasicHttpBinding_IService" />
</client>
</system.serviceModel>
</configuration>
My webservioce is like (it is a WCF website in which the port is provided by me and is 2000
Service contract is
[ServiceContract]
public interface IService
{
[OperationContract]
Message GetMessage(Message s);
}
[ServiceBehavior]
public class Service : IService
{
public Message GetMessage(Message message)
{
string body = message.GetBody<string>();
return Message.CreateMessage(MessageVersion.Soap11, "http://tempuri.org/IWebService/GetMessageResponse", "body is " + body);
}
}
and the web.config is
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint address="http://localhost:2000/WebService/Service.svc" binding="basicHttpBinding" bindingConfiguration=""
contract="IService" >
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<timeouts closeTimeout="00:01:10" />
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" policyVersion="Policy15" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
My issue is 405 webmethod not body can anyone please tell me what is an issue in this, I am new to WCF before this created a sample and this is my second application
You do not need to create the SOAP message manually, just use basic http binding and that will rturn SOAP.
When you have a WCF service, the whole point is that you can define e.g. parameters like strings, int and so forth - and you don't have to mess with loads of XML and SOAP headers and bodies.
So basically, your service contract should be something like:
[ServiceContract]
public interface IService
{
[OperationContract]
int DoSomeMathAddTowNumbers(int num1, int num2);
}
and your service implementation would then just implement that method, add the two numbers, and return the result:
public class Service : IService
{
int DoSomeMathAddTowNumbers(int num1, int num2)
{
return num1 + num2;
}
}
No mess with Message or XML manipulation or anything.
A client that wants to call your service would create a WCF client-side proxy using svcutil or the Visual Studio Add Service Reference method, and it would get a proxy class that has the same methods as the service it connects to - and you would call them, using the straight, easy parameters - something like:
ServiceClient client = new ServiceClient();
int result = client.DoSomeMathAddTwoNumbers(42, 100);
So basically, I think you need to get back to the drawing board and read up on the WCF basics again - it should not be that difficult, really! (that's the whole point - it should make services easy ...)
Check out the Beginner's Guide at the WCF Developer Center at MSDN - it contains lots of really good videos, screencasts, articles on how to get started with WCF.-
You might also want to check out the DotNet Rocks TV episode #135: Keith Elder Demystifies WCF