Suprime .svc in URL of WCF-C# - wcf

I start to work with WCF - C#, because I need to make a big scale project, and I found the follow problem:
I have tried to erase in the URL of a service WCF the .svc extension with following code:
using System.Web;
namespace PruebaWCFEndpoint
{
public class RemoveSvc : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += delegate
{
HttpContext ctx = HttpContext.Current;
string path = ctx.Request.AppRelativeCurrentExecutionFilePath;
path = path.Replace("Hola.svc", "Hola");
ctx.RewritePath(path, null, ctx.Request.QueryString.ToString(), false);
};
}
}
}
and the following code is the web.config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false 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="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="ApplicationInsightsWebTracking"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
preCondition="managedHandler"/>
<!--
The follow line was added by myself *************
-->
<add name ="removesvc" type="PruebaWCFEndpoint.RemoveSvc,PruebaWCFEndpoint"/>
<!--
******************************
-->
</modules>
<directoryBrowse enabled="true"/>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
</configuration>
But I am tring to test and the "WCF Test client" tool show the following message:
Error: Cannot obtain Metadata from http://localhost:9086/Hola.svc If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address. For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange Error URI: http://localhost:9086/Hola.svc Los metadatos contienen una referencia que no se puede resolver: 'http://localhost:9086/Hola.svc'. El tipo de contenido text/html; charset=utf-8 del mensaje de respuesta no coincide con el tipo de contenido del enlace (application/soap+xml; charset=utf-8). Si usa un codificador personalizado, aseg£rese de que el m‚todo IsContentTypeSupported se implemente correctamente. Los primeros 1024 bytes de la respuesta fueron: '
HTTP Error 500.0 - Internal Server Error
The service interface is the follow:
using System.ServiceModel;
namespace PruebaWCFEndpoint
{
[ServiceContract]
public interface IHola
{
[OperationContract]
string saludar(string nombre);
}
}
and their implementation is the follow:
namespace PruebaWCFEndpoint
{
public class Hola : IHola
{
public string saludar(string nombre)
{
return "hola" + nombre;
}
}
}

Related

WCF service not show metadata on server (return 404), only locally it works

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.

Wcf returns "success" just for first time and subsequent calls return "timeout"

I researched this problem but i couldn't find any useful result.
I tried to configure web.config and iis configurations (disabling cache etc.) but result is negative.
When i make request as restful using wcf, some of wcf methods works fine for everytime but some of wcf methods work just first time returning success, subsequent calls' results return "timeout".
When i restart iis and , i end iis worker task on the task manager and i debug wcf service, troubled methods work fine just first time.
Please help me
Thank you in advance
For Ex:
[REQUEST] localhost/Service1.svc/GetData?value=8
[RESPONSE] "You entered: 8"
GetData method already works fine
but for Arm method;
[REQUEST first] localhost/Service1.svc/Arm?pass=1234&type=2
[RESPONSE first] {"Data":true,"Error":false,"Message":"Success"}
[REQUEST subsequents] localhost/Service1.svc/Arm?pass=1234&type=2
[RESPONSE subsequents] {"Data":false,"Error":true,"Message":"Request timeout. Please try again later"}
---Service1.svc.cs---
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(IncludeExceptionDetailInFaults = true, InstanceContextMode = InstanceContextMode.PerCall)]
public class Service1 : IService1
{
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "GetData?value={value}")]
//stable method
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "Arm?pass={pass}&type={type}")]
//troubled method
public ReturnType<bool> Arm(string pass, int type)
{
ParadoxFunctions pf = new ParadoxFunctions(pass);
ReturnType<bool> ret = new ReturnType<bool>();
ParadoxReturn pr = pf.ArmPanel(type);
if (pr.Success)
{
ret.Error = false;
ret.Message = pr.Message;
ret.Data = true;
}
else
{
ret.Message = pr.Message;
}
return ret;
}
}
---Web.config---
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.webServer>
</system.webServer>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime targetFramework="4.0" requestValidationMode="2.0" maxRequestLength="65536000"/>
<pages validateRequest="false" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding maxReceivedMessageSize="65536000" transferMode="StreamedRequest">
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior>
<webHttp defaultOutgoingResponseFormat="Json"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false 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="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="webHttpBinding" scheme="http"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="ApplicationInsightsWebTracking"/>
</modules>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.2.28.0" newVersion="4.2.28.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Selfhosting WCF Service and basicHttpBinding: A Windows identity that represents the caller is not provided by binding

I have a self hosting wcf service in a console application.
A simple self hosting service is no problem, there are enough examples.
Now I want to impersonate the caller of the wcf service. Although I followed this msdn article http://msdn.microsoft.com/en-us/library/ff648505.aspx I get follwing error:
The contract operation 'GetProduct' requires Windows identity for automatic impersonation. A Windows identity that represents the caller is not provided by binding
Here is my App.config of the wcf service in the CONSOLE application:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="SelfHostingWCFService.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<SelfHostingWCFService.Properties.Settings>
<setting name="URL" serializeAs="String">
<value>http://localhost:8081/ProductService</value>
</setting>
</SelfHostingWCFService.Properties.Settings>
</applicationSettings>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ProductServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceAuthorization impersonateCallerForAllOperations="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="SelfHostingWCFService.ProductService"
behaviorConfiguration="ProductServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8081/ProductService"/>
</baseAddresses>
</host>
<endpoint address="soap" binding="basicHttpBinding" contract="SelfHostingWCFService.IProductService"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
</configuration>
Here ist the Service Code:
public class ProductService : IProductService
{
[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public Product GetProduct(int productId)
{
Product prod = new Product();
prod.ID = productId;
prod.Name = productId.ToString() + " XDS";
return prod;
}
[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public string User()
{
string Name = string.Empty;
if (OperationContext.Current.ServiceSecurityContext != null)
Name = OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name;
if (ServiceSecurityContext.Current != null)
Name = ";" + ServiceSecurityContext.Current.WindowsIdentity.Name;
Name = ";" + Thread.CurrentPrincipal.Identity.Name;
return Name;
}
}
Here is the client code:
private void button1_Click(object sender, EventArgs e)
{
ProductService.ProductService srv = new ProductService.ProductService();
//srv.Credentials = System.Net.CredentialCache.DefaultCredentials;
ProductService.Product prod = srv.GetProduct(1, true);
label1.Text = prod.Name;
label2.Text = srv.User();
}
What do I making wrong?
Please let me know.
Can I use basicHTTPBinding or must I use wsHTTPBinding?
many thanks for your help
I don't see your client-side configuration - you may need to set your client binding Security.Transport.ClientCredentialType
See here: http://msdn.microsoft.com/en-us/library/ms729700(v=vs.110).aspx

Windows Service Bus 1.0, Appfabric, Netmessagingbinding failuring

I seem to run into the same problem over and over again when I am trying to host a WCF service in Windows Server AppFabric that uses netmessagingbinding to receive messages from Windows Service Bus 1.0 queues. AppFabric aborts the service, so if I press F5 on service?wsdl then I sometimes get failures, sometimes I get a nice WSDL generated. Where is my mistake? It is rather impossible to find an example that uses AppFabric, netmessagingbinding and Windows Service Bus (not Azure), so I haven't been able to finde my mistake...
[ServiceContract]
public interface ISBMessageService
{
[OperationContract(IsOneWay = true, Action = "DoSomething")]
[ReceiveContextEnabled(ManualControl = true)]
void DoSomething(string something);
}
[ServiceBehavior]
public class SBMessageService : ISBMessageService
{
[OperationBehavior]
public void DoSomething(string something)
{
Trace.WriteLine(String.Format("You sent {0}", something));
// Get the BrokeredMessageProperty from the current OperationContext
var incomingProperties = OperationContext.Current.IncomingMessageProperties;
var property = incomingProperties[BrokeredMessageProperty.Name] as BrokeredMessageProperty;
ReceiveContext receiveContext;
if (ReceiveContext.TryGet(incomingProperties, out receiveContext))
{
receiveContext.Complete(TimeSpan.FromSeconds(10.0d));
}
else
{
throw new InvalidOperationException("...");
}
}
}
<?xml version="1.0"?>
<configuration>
<appSettings>
<!-- Service Bus specific app setings for messaging connections -->
<add key="Microsoft.ServiceBus.ConnectionString"
value="Endpoint=sb://LRNcomp/LRNnamespace"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
</system.web>
<system.serviceModel>
<!-- These <extensions> will not be needed once our sdk is installed-->
<extensions>
<bindingElementExtensions>
<add name="netMessagingTransport" type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingTransportExtensionElement, Microsoft.ServiceBus, Version=1.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</bindingElementExtensions>
<bindingExtensions>
<add name="netMessagingBinding" type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingBindingCollectionElement, Microsoft.ServiceBus, Version=1.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</bindingExtensions>
<behaviorExtensions>
<add name="transportClientEndpointBehavior" type="Microsoft.ServiceBus.Configuration.TransportClientEndpointBehaviorElement, Microsoft.ServiceBus, Version=1.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</behaviorExtensions>
</extensions>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false 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" httpHelpPageEnabled="True"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="securityBehavior">
<transportClientEndpointBehavior>
<tokenProvider>
<sharedSecret issuerName="owner" issuerSecret="somthing"/>
</tokenProvider>
</transportClientEndpointBehavior>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<netMessagingBinding>
<binding name="messagingBinding" closeTimeout="00:03:00" openTimeout="00:03:00" receiveTimeout="00:03:00" sendTimeout="00:03:00" sessionIdleTimeout="00:01:00" prefetchCount="-1">
<transportSettings batchFlushInterval="00:00:01"/>
</binding>
</netMessagingBinding>
</bindings>
<services>
<service name="SBExamples.SBMessageService">
<endpoint name="Service1" address="sb://LRNcomp:9354/LRNnamespace/test/myqueue2" binding="netMessagingBinding" bindingConfiguration="messagingBinding" contract="SBExamples.ISBMessageService" behaviorConfiguration="securityBehavior"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
An error in the WCF contract generated many strange exceptions, like my transport channel was aborted. Proper sharing of contract between sender and receiver did the trick.

cant get fiddler to record requests from wcftestclient.exe?

I build a very basic wcf service using visual studio development server just to see fiddler working:
c#
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="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"/>
<!-- 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>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
when I run the wcftestclient it shows up the getdata() works but does not show up in fiddler? how can i amend this?
thanks
P
What is address of your service? If you use localhost or 127.0.0.1 these messages won't be captured. Use your machine name or network IP address. You can set it in Project properties or directly on the endpoint.