Custom ASP.NET Forms Authentication Service with WCF - wcf

I am trying to create a custom ASP.NET Forms Authentication Service using WCF. I am calling it via a test page that contains only a single line of JS (except for the ScriptManager scripts). The problem is that the server returns response code 500 and the response body is empty. My breakpoints in the service method and in the Application_Error in Global.asax are not being hit.
Sys.Services.AuthenticationService.login('user', 'pass', false, null, null, null, null, null);
I can see the request go to the server in the browser tools with the following request body:
{"userName":"user","password":"pass","createPersistentCookie":false}
Other things on the request side also seem fine.
Here is the configuration service:
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="BtxAuthenticationEndpointBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
</serviceBehaviors>
</behaviors>
<services>
<service name="MyNamespace.BtxAuthenticationService">
<endpoint contract="MyNamespace.IBtxAuthenticationService" binding="webHttpBinding" behaviorConfiguration="BtxAuthenticationEndpointBehavior"/>
</service>
</services>
</system.serviceModel>
And the declaration of the interface:
[ServiceContract]
public interface IBtxAuthenticationService
{
[OperationContract]
[WebInvoke]
bool Login(string username, string password, bool createPersistentCookie);
[OperationContract]
[WebInvoke]
void Logout();
}
The implementation:
public class BtxAuthenticationService : IBtxAuthenticationService
{
public bool Login(string username, string password, bool createPersistentCookie)
{
... irrelevant because this is never hit
}
public void Logout()
{
}
}
Can someone tell me how to configure this or point me to a way to debug it. An article about implementing custom Forms Authentication with a WCF service will be welcome too. I've tried experimenting with various other settings including all the exception details settings I could find but could not make any progress (though I was able to make some regress and get different exceptions like missing endpoints and so on).
Thank you for your time.

Not sure if this helps. I have never written such service but your configuration creates WCF service wich is not ASP.NET AJAX ready and works with XML instead of JSON. Try to use this instead of webHttp behavior:
<endpointBehaviors>
<behavior name="BtxAuthenticationEndpointBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>

Related

Calling WCF Service from both Jquery and a Service Reference

My requirement is to be able to call a simple WCF service from both Jquery Ajax and also by adding a service reference.
This is easily done in asmx services and I am really struggling to see how WCF can be "better" and "more powerful" when this simple task is proving so difficult and convoluted.
I have followed various tutorials such as:
http://www.codeproject.com/Articles/132809/Calling-WCF-Services-using-jQuery
http://www.codeproject.com/Articles/540169/CallingplusWCFplusServicespluswithplusjQuery-e2-80
http://blog.thomaslebrun.net/2011/11/jquery-calling-a-wcf-service-from-jquery/#.UihK6saa5No
However I always end up with a solution where I can call by ServiceReference but not Jquery or vice-versa.
For the following simple service, can anyone please provide me with the:
Necessary attributes to decorate the service and interface with
Web.config ServiceModel sections with all bindings/endpoints/behaviours/etc
to facilitate calling the WCF service from both Jquery (ajax) and by adding a service reference in a .net project?
Or should I just go back to good old simple (but apparently less powerful) amsx?
I have used webhttpbinding for the WCF service to be called from javascript.
Web.config:
<system.serviceModel>
<services>
<service name="WCF.TestWCF" behaviorConfiguration="TestWCFBehaviour">
<endpoint address="" binding="webHttpBinding" contract="WCF.ITestWCF" behaviorConfiguration="TestWCFEndPointBehaviour"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="TestWCFBehaviour">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="TestWCFEndPointBehaviour">
<enableWebScript/>
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
service:
namespace WCF{
[ServiceContract(Namespace = "Saranya")]
public interface ITestWCF
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Xml)]
String HelloWorld();
}}
namespace WCF{
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
public class TestWCF:ITestWCF
{
public String HelloWorld()
{
return "Hello World!!";
}
}
Using Jquery:
$.post("http://localhost:26850/Service1.svc/HelloWorld?", null, fnsuccesscallback, "xml");
function fnsuccesscallback(data) {
alert(data.xml);
}
using service reference:
obj = new Saranya.ITestWCF();
obj.HelloWorld(fnsuccesscallback);
function fnsuccesscallback(data) {
alert(data.xml);
}

WCF 4 RESTful with HTTPS GET, POST or PUT

I'm desperately in need of a working example of a WCF 4 RESTful web service. Our SaaS ticketing system (zendesk.com) can communicate with an URL target using HTTP GET, POST or PUT. I have not done any web related work (only c# console apps) but have now been tasked to create a WCF 4 web service with the following requirements:
Secured via HTTPS
Secured via username / password
Read and process the data from the SaaS system that is transmitted as application/x-www-form-urlencoded information, for example:
http://somedomain/a/path?value=message+with+placeholders+evaluated
My current code is as follows:
namespace WcfService2
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke]
void ClearAlert(Stream input);
}
}
namespace WcfService2
{
public class Service1 : IService1
{
public void ClearAlert(Stream input)
{
StreamReader rawTicketData = new StreamReader(input);
string ticketData = rawTicketData.ReadToEnd();
rawTicketData.Dispose();
//Do some work with ticketData
}
}
}
The web.config file:
<services>
<service behaviorConfiguration="MetaDataBehavior" name="WcfService2.Service1">
<endpoint behaviorConfiguration="RestBehavior" binding="webHttpBinding" bindingConfiguration="" name="REST" contract="WcfService2.IService1" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="RestBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<behaviors>
I am currently using only HTTP (not HTTPS) for development and testing hence the missing binding entry / entries for HTTPS as well as any entries for login purposes in the web.config, at least I assume that is what / where I need to add the needed configuration but again, I have no knowledge.
I would more than appreciate any help / assistance I can get in creating a web service with the three above described requirements.
Thanks to all!
William

Not getting the expected results from WCF REST Service (Newbie)

I'm new to WCF Web Services. I'm trying to test my simple hello world web service.
For now, I'm doing self hosting. I'm at the point where I've started the host application, opened my browser and typed in the address to my resource. I've also run Fiddler and created a Request by using the Composer. In both cases, I get the "You have created a service." page that has a link to my .wsdl.
I was expecting to see the "Hello World" text in my Response or a web page that has "...Hello world".
What am I missing? or am I just misunderstanding the process?
App.Config
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="My.Core.Services.GreetingService" behaviorConfiguration="MyServiceTypeBehaviors">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/greeting"/>
</baseAddresses>
</host>
<endpoint name="GreetingService" binding="webHttpBinding" contract="My.Core.Services.IGreetingService"/>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceTypeBehaviors" >
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
Host code
using System;
using System.ServiceModel;
using My.Core.Services;
namespace My.Service.Host
{
class Program
{
static void Main(string[] args)
{
using (var host = new ServiceHost(typeof(GreetingService)))
{
host.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();
host.Close();
}
}
}
}
Hello World Contract and Service
using System.ServiceModel;
using System.ServiceModel.Web;
namespace My.Core.Services
{
[ServiceContract]
public interface IGreetingService
{
[OperationContract]
[WebGet(UriTemplate = "/")]
string GetGreeting();
}
}
using System.Collections.Generic;
namespace My.Core.Services
{
public class GreetingService : IGreetingService
{
public string GetGreeting()
{
return "Greeting...Hello World";
}
}
}
If I understand you correctly, you can see your wsdl link at the following url
http://localhost:8080/greeting
In order to now call your endpoint, you need to add it to the url like this
http://localhost:8080/greeting/GetGreeting/
I'm not entirely sure why you have the UriTemplate thing in there though other than my guessing that you probably just copy pasted it from an example. Unless you have specific query string parameters that you want defined, you don't really need it and it kind of tends to complicate things so I'd recommend taking it out. That means your Interface would look something like this...
[ServiceContract]
public interface IGreetingService
{
[OperationContract]
[WebGet]
string GetGreeting();
}
...and you can then lose the final "/" on the url.
I figure out the problem. When I use the url: "http://localhost:8080/greeting" the server sends the temp page. When I add the backslash "/" on the end of the url it execute my service.
so, "http://localhost:8080/greeting/" works and sends me the "...Hello World" back.

Two WCF services cannot interact when on same server

I have two WCF services hosted with a hosting provider. Both service to work fine. I can access them from my own computer or even from a website hosted with another provider. The weird part (at least, the part I don't understand) is; one cannot call the other.
Both services are located in a subfolder of the web root, at the same hierarchical level. Like wwwroot\serviceone and wwwroot\servicetwo. Both are marked as application folder in IIS en both have an almost similar web.config as shown below, only the names differ:
<configuration>
<system.web>
<compilation targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="servone">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<services>
<service name="MyService.ServiceOne" behaviorConfiguration="servone">
<endpoint address="" binding="basicHttpBinding" contract=" MyService.IServiceOne "/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Browsing to the .svc displays the well-known service page with the example code;
class Test
{
static void Main()
{
ServiceOne client = new ServiceOne ();
// Use the 'client' variable to call operations on the service.
// Always close the client.
client.Close();
}
}
The client has a method named HandleRequest(string str). So in my code (C#) there's a line like;
client.HandleRequest("blah");
The call doesn't raise an exception (I can tell because they are catched, handled and written to a database). It's like the message is sent but never returns.
When I run this service (who calls the other) locally and leave the second on the remote server, all works well.
Obvious it is hard to provide all the details from the hosting party. Unfortunate I don't have access to an IIS installation to simulate the environment either. So, I'm not expecting an in-depth technical solution based on the little information I can provide. But any comment about how this setup differs from all others might be helpful.
I really appreciate any effort, thanks.
Edit:
The call is made like this:
public bool Send(String str)
{
bool result = false;
BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress ep = new EndpointAddress("http://www.mydomain.com/ServiceTwo.svc");
client = new ServiceTwoClient(b, ep);
//
try
{
result = client.HandleRequest(str);
client.Close();
return result;
}
catch (Exception x)
{
Add2DbLog(x.Message);
return false;
}
}
The domain alias you're using may not work locally on the server. Log in to that server, launch a web browser, and navigate to the service URL used in your code (http://www.mydomain.com/ServiceTwo.svc). Ensure that you don't get any error messages.

WCF, MVC2, obtaining access to auto generated WSDL and working through default endpoint not found issues

I’m trying to run a very basic web service on the same IIS7 website that runs a MVC2 application. This is presenting a couple of different issues, and I believe it has to do with my system.serviceModel, but obviously I don’t know for sure (or I would fix it).
On the server side I can run my service just fine, the help operation works like a charm. I can execute the default WCF operation GetData and supply a value through the FireFox address bar.
http://localhost/services/service1/getdata?value=3 (example)
The first problem I’m having is that when I navigate to the base service URI it will display the message below. While this isn’t the end of the world because I can still execute code by manipulating the address; I do expect something else to be displayed. I expect the standard new web service message explaining that by appending “?wsdl” to the address you will receive the auto generated WSDL. I cannot access my auto generated WSDL.
“Endpoint not found. Please see the
service help page for constructing
valid requests to the service.”
Problem number two is in regard to client applications connecting to my web service. I created a console application in separate Visual Studio solution and added a web service reference to Service1. In the Visual Studio tool I can see and use the two methods that exist in my service, but when I run the code I get the following exception.
InvalidOperationException Could not
find default endpoint element that
references contract
'ServiceReference1.IService1' in the
ServiceModel client configuration
section. This might be because no
configuration file was found for your
application, or because no endpoint
element matching this contract could
be found in the client element.
Before I post my code (I’m sure readers are tired of reading about my struggles) I do want to mention that I’ve been able to run a WCF Service Library and Console application in the same solution flawlessly. There seems to be very few resources explaining WCF, WCF configuration, and working with MVC. I’ve read through several articles and either they were out-of-date or they were so simplistic they were nearly useless (e.g. click button receive web service named “Service1”).
To summarize; why am I not able to access the auto generated WSDL and how can I successfully connect my client and use the web service? Now the best part; the code.
Global.asax
//Services section
routes.Add(new ServiceRoute("services/service1", new WebServiceHostFactory(), typeof(Service1)));
Web.Config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="DefaultEndpoint" helpEnabled="true" automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
<mexEndpoint />
</standardEndpoints>
<services>
<service name="Project.Services.Service1" behaviorConfiguration="MetadataBehavior">
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint endpointConfiguration="DefaultEndpoint" kind="webHttpEndpoint" binding="webHttpBinding" contract="Project.Services.IService1" />
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MetadataBehavior">
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="false" /> <!-- httpGetEnabled="true" does not solve the problem either -->
<!-- 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>
</behaviors>
</system.serviceModel>
IService1
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET")]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
Service1
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
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;
}
}
Client Program
class Program
{
static void Main(string[] args) {
Service1Client client = new Service1Client();
client.GetData(2);
}
}
Thanks for the help! The problem was inside of my Global.asax.cs.
Original:
routes.Add(new ServiceRoute("services/service1", new WebServiceHostFactory(), typeof(Service1)));
New:
routes.Add(new ServiceRoute("services/service1", new ServiceHostFactory(), typeof(Service1)));
The difference was chaing the host factory from "WebServiceHostFactory" to "ServiceHostFactory".
The second part of my question regarding client connections is because configuration settings are not being generated. I have to manually type them for each client. Yikes!
To avoid manually typing client configuration I had to change my endpoint
Original
<endpoint endpointConfiguration="DefaultEndpoint" kind="webHttpEndpoint" binding="webHttpBinding" contract="Project.Services.IService1" />
New
<endpoint binding="wsHttpBinding" contract="Project.Services.IService1" />
After making this change the service and client are working flawlessly.
A quick answer to one of your questions:
To summarize; why am I not able to
access the auto generated WSDL
<serviceMetadata httpGetEnabled="false" />
...needs to be
<serviceMetadata httpGetEnabled="true" />
...in order to be able to retrieve the WSDL over http. You have to tell WCF to generate service metadata, and you've told it not to.