Greeting, Currently i am working on a displaying the services in xml format in the browser.
However, it shows an empty page, is there an explanation why? firewall issue?
Here are all the files.
IProductService1.cs
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WCFRESTfulService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IProductService1
{
[OperationContract]
[WebGet]
List<product> GetAllProducts();
[OperationContract]
[WebGet]
product GetProducts(string id);
}
}
ProductService1.svc.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCFRESTfulService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
public class Service1 : IProductService1
{
public List<product> GetAllProducts()
{
using(var db=new estocktakeEntities())
{
return db.products.ToList();
}
}
public product GetProducts(string id)
{
Int32 _id = Convert.ToInt32(id);
using(var db=new estocktakeEntities())
{
return db.products.SingleOrDefault(p => p.invtid == id);
}
}
}
}
Web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="myService.ProductService">
<endpoint address="" behaviorConfiguration="" binding="webHttpBinding" contract="MyService.IProductService"></endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="restbehaviour">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add scheme="https" binding="basicHttpBinding"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true"></serviceHostingEnvironment>
</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>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="Model1" connectionString="data source=CHRISPHAN-HP\SQLEXPRESS;initial catalog=estocktake;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" /><add name="estocktakeEntities" connectionString="metadata=res://*/productmodel.csdl|res://*/productmodel.ssdl|res://*/productmodel.msl;provider=System.Data.SqlClient;provider connection string="data source=CHRISPHAN-HP\SQLEXPRESS;initial catalog=estocktake;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
</configuration>
When i tested it using WCF test tool, the functions are working.
Tested on website
After adding the function into the url
Any suggestion will be a great help, Sorry for this long post.
-UPDATE-
Still unable to run services in the browser, when it is possible in the youtube video.
Using
VS2013 for web
SQL
IIS Express
Generally browsers does not display xml results, To call WCF methods from a browser, you need need to create Restful service in WCF
The following link should help,
Run WCF methods from a browser
Related
I create a client application that get data from my rest wcf service as you can see :
Uri reqUri = new Uri("https://localhost/paymentservice.svc/listpayment");
WebRequest req = WebRequest.Create(reqUri);
req.PreAuthenticate = true;
NetworkCredential credential = new NetworkCredential("test", "test123");
req.Credentials = credential;
WebResponse resp = req.GetResponse();
DataContractSerializer data = new DataContractSerializer(typeof(string));
var res = data.ReadObject(resp.GetResponseStream());
Console.WriteLine(res);
Console.ReadLine();
I create a certificate in iis as you can se :
And upload my published file on it .
But when i call my client i get this error :
An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel
Here is my service webconfig
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
<authentication mode="None" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="secureHttpBinding">
<security mode="Message">
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="Payment.Application.ServiceImplement.PaymentService" behaviorConfiguration="customBehaviour">
<endpoint address=""
binding="webHttpBinding"
contract="Payment.Domain.Service.IPaymentService"
behaviorConfiguration="web"/>
</service>
<service name="Payment.Infrustructure.RepositoryImplement.PaymentRepository" behaviorConfiguration="customBehaviour" >
<endpoint address=""
binding="webHttpBinding"
contract="Payment.Domain.Repository.IPaymentRepository"
behaviorConfiguration="web"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="customBehaviour">
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="Payment.Service.UserAuthentication,Payment.Service"/>
</serviceCredentials>
<!-- 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>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="GET, POST,PUT,DELETE" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true">
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</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>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.;initial catalog=SymfaDB;user id= sa ;password=12345;" providerName="System.Data.SqlClient" />
<!--<add name="DefaultConnection" connectionString="Data Source=92.50.12.222,1433;initial catalog=ParkingDB;user id= sa ;password=123qweQWE#;" providerName="System.Data.SqlClient" />-->
</connectionStrings>
</configuration>
When irun the project in visual studio and call this url http://localhost:4428/PaymentService.svc/listpayment I get the data as you can see :
But when i upload the publish file into iis and call this url https://localhost/PaymentService.svc/listpayment as you can see i get this error :
As you can see when i call this https://localhost/PaymentService.svc my service is available .
You need to install the certificate as trusted source.
Open a command prompt with admin rights, type "mmc" and press enter which will open Microsoft Management Console.
From Menu go to File > Add/Remove Snap-In, select Certificates and Click Add
Select Computer Account and click Next, select Local Computer and click Finish.
Go to Certificates (Local Computer) > Personal > Certificates
From the Menu go to Action > All Tasks > Import
Click Next in the Certificate Import Wizard, Provide the path to the certificate file, enter the password if any then click Next, Next and Finish.
Now you will be back to Microsoft Management Console, click on Trusted Root Certification Authorities, select Certificates, Action > All Tasks > Import and follow the step 6.
Also the hostname used in the URL should match the name that's on certificate. Make sure the URL you're using and the URL on the 'Issued to' field of the certificate are the same.
To get rid of this error use the machine name exactly same as your certificate section “Issued to” says. For example, if you open your certificate then you’ll see issued to property and which should be your Machine name. If your machine is part of a domain then machine name would be like .. etc, so if you open it in your browser will fully qualified name of your machine then you won’t be getting that error.
So i just call my service by domain like https://union-pc58.union.com/Service1.svc
Just follow this link
http://www.c-sharpcorner.com/UploadFile/vendettamit/create-secure-wcf-rest-api-with-custom-basic-authentication/
this might be very common question and asked many times but I troubleshooting this issue from the past 2 days.
I have created WCF service below:
IStudentService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
namespace WcfStudentService
{
// Defines IStudentService here
[ServiceContract ]
public interface IStudentService
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
string GetData();
}
}
StudentService.svc.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Newtonsoft.Json;
namespace WcfStudentService
{
// StudentService is the concrete implmentation of IStudentService.
public class StudentService : IStudentService
{
public string GetData()
{
return "{ Result : " + "Success" + " }";
}
}
}
Web.config(Updated):
<?xml version="1.0" encoding="UTF-8"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<appSettings />
<connectionStrings />
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true" targetFramework="4.0" />
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows" />
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<pages controlRenderingCompatibilityVersion="4.0" clientIDMode="AutoID" />
</system.web>
<system.web.extensions>
<scripting>
<webServices>
<!--
Uncomment this section to enable the authentication service. Include
requireSSL="true" if appropriate.
<authenticationService enabled="true" requireSSL = "true|false"/>
-->
<!--
Uncomment these lines to enable the profile service, and to choose the
profile properties that can be retrieved and modified in ASP.NET AJAX
applications.
<profileService enabled="true"
readAccessProperties="propertyname1,propertyname2"
writeAccessProperties="propertyname1,propertyname2" />
-->
<!--
Uncomment this section to enable the role service.
<roleService enabled="true"/>
-->
</webServices>
<!--
<scriptResourceHandler enableCompression="true" enableCaching="true" />
-->
</scripting>
</system.web.extensions>
<!--
The system.webServer section is required for running ASP.NET AJAX under Internet
Information Services 7.0. It is not necessary for previous version of IIS.
-->
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<services>
<!--Garvit: Commented below code-->
<!--<service name="WcfStudentService.StudentService" behaviorConfiguration="WcfStudentService.StudentServiceBehavior">-->
<service name="WcfStudentService.StudentService" behaviorConfiguration="jsonRestDefault">
<!--Garvit:Host Tag added-->
<host>
<baseAddresses>
<add baseAddress="http:/192.168.X.XXX"/>
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!--<endpoint address="" binding="webHttpBinding" contract="WcfStudentService.IStudentService">-->
<!--Garvit: Added below endpoint and commented above-->
<endpoint behaviorConfiguration="RESTFriendly" binding="webHttpBinding" contract="WcfStudentService.IStudentService">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="jsonRestDefault">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="RESTFriendly">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<defaultDocument>
<files>
<add value="StudentService.svc" />
</files>
</defaultDocument>
</system.webServer>
</configuration>
The above service returns the result when I call it from WcfTestClient but when I browse my service URL on browser like(192.168.X.XXX:8282/IStudentService.svc/GetData) it throws 404 error.
I google and found these two below threads usefull:
Thread1
Thread2
But still its not working. Please help.
Any help
I have created a Entity Framework DLL EMPDAL which points to Employees Table of Northwnd database. Below is the code for Entity framework
namespace EmpDAL{
public class EmplooyeeData
{
public static List<Employee> GetEmployees( int EmployeeId)
{
using (DbEntities dbContext = new DbEntities())
{
return dbContext.Employees.Where(x => x.EmployeeID == EmployeeId).ToList();
}
}
public static void SaveEmployee(Employee emp)
{
DbEntities dbContext = new DbEntities();
dbContext.Employees.Add(emp);
dbContext.SaveChanges();
}
}}
Below is the Appconfig file of EMPDAL
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DbEntities" connectionString="metadata=res://*/EmployeeModel.csdl|res://*/EmployeeModel.ssdl|res://*/EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=NorthWnd;user id=sa;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>
Below is the code for the WCF service
namespace EmployeeService{
public class EmployeeService : IEmployeeService
{
public List<EmpDAL.Employee> GetEmployees(int Empid)
{
return EmpDAL.EmplooyeeData.GetEmployees(Empid);
}
public void SaveChanges(EmpDAL.Employee emp)
{
EmpDAL.EmplooyeeData.SaveEmployee(emp);
}
}}
Below is the AppConfig for WCF EmployeeService
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="EmployeeService.EmployeeService">
<endpoint address="" binding="basicHttpBinding" contract="EmployeeService.IEmployeeService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/Design_Time_Addresses/EmployeeService/EmployeeService/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel> <configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <connectionStrings>
<add name="DbEntities"connectionString="metadata=res://*/EmployeeModel.csdl|res://*/EmployeeModel.ssdl|res://*/EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=NorthWnd;user id=sa;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory,EntityFramework" /> </entityFramework></configuration>
When client uses the WCF service it and when it tries to execute "using (DbEntities dbContext = new DbEntities())" it goes to
public partial class DbEntities : DbContext {
public DbEntities()
: base("name=DbEntities")
and throws exception
typeinitializationexception was unhandled .The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception.
It is very generic exception so in your editor try reading the whole details of the exception and then resolve it.
For me, it was due to the entity framework version written in webconfig file and actual file included ,there was difference and also i had to remove providers tag in web config file of my project
After getting input in another thread here on the forum [StackOverFlow][1]
[1]: Getting a nullreference when passing a complex object from KSOAP2 to WCF have i reached conclusion that my problem is with the WCF service itself. It seems that the service is not able to understand the object that it's receiving.
No matter what I do the object passed is always null.
I have even tried declaring the datamember explicit even though it should not be necessary in the current version of WCF.
Here's the class I'm trying to pass through the WCF:
namespace ModelLayer
{
[DataContract]
public class User
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string UserName { get; set; }
[DataMember]
public string Mac { get; set; }
public User()
{
}
}
}
My service interface:
[ServiceContract (Namespace = "http://nordahl.org/")]
public interface IWcfFoodAndAllergi
{
[OperationContract]
int InsertUser(User _user);
[OperationContract]
User GetUser(string _mac);
[OperationContract]
int InsertRecipe(Recipe _recipe);
[OperationContract]
List<Recipe> GetRecipeByAllergi(List<Allergies> _allergies);
[OperationContract]
List<Recipe> GetRecipeByType(string _type);
[OperationContract]
List<Recipe> GetRecipeByName(string _name);
}
}
And lastly the webconfig file itself:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" maxRequestLength="1048576"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
<fileExtensions allowUnlisted="true">
<remove fileExtension=".cs"/>
<add fileExtension=".cs" allowed="true"/>
</fileExtensions>
</requestFiltering>
</security>
</system.webServer>
<system.serviceModel>
<services>
<service name="WcfFoodAndAllergi.WcfFoodAndAllergi">
<!-- Use a bindingNamespace to eliminate tempuri.org -->
<endpoint address=""
binding ="basicHttpBinding"
bindingNamespace="http://nordahl.org/"
contract="WcfFoodAndAllergi.IWcfFoodAndAllergi"
/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name ="">
<!-- 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"/>
<!--
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>
I had a similar problem to yours when a complex object referenced another complex object in a T4 generated class. If you are using an include in an obtain method, or another method relating to Entity or objects linking complex objects to each other; you may get a circular reference error. I had a friend show me how to fix this with a custom class that sets up an attribute:
Complex Object won't return when using 'include' syntax in WCF with Entity Version 6
I have ASP.NET MVC 4 application with user authentication based on SimpleMemebershipProvider. Using Ms SQL database. Everything works fine. I can register new users, log in, log-out etc.
The problem is that I want to create Windows forms application which can connect to the server and after passing credentials it can validate if user exists in database (registered through MVC) and if so, do some stuff, for example change username or password. My idea is to use WCF service library. I know the basic idea of WCF or at least i hope so :) I know that there is possibility to authenticate users.
I was searching the web but i didn't found how to do this with simplememebership provider. I've also tried to write WCF Service library on my own and I've created something like this below but it doesn't work. When I'm testing and put wrong credentials it returns string "bad credentials" which is good. However when i type in valid credentials it shows me an error "NullReference exception" on line:
if (WebSecurity.Login(UserName, password, persistCookie: false)).
I don't think it's secure either :/
Can somebody explain me how to this or what I'm doing wrong ?? Or maybe there is better solution than WCF ?
Sevice1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using WebMatrix.WebData;
using System.Web.Mvc;
namespace AR_WCF_Library
{
// 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 Service1 : IService1
{
public string GetData(string UserName, string password)
{
WebSecurity.InitializeDatabaseConnection("MyDB", "UserProfile", "UserId", "UserName", autoCreateTables: false);
if (WebSecurity.Login(UserName, password, persistCookie: false))
{
return string.Format("Hello: {0}", UserName);
}
else
{
return "bad credentials";
}
}
}
}
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<connectionStrings>
<add name="MyDB" connectionString="Data Source=SERWER\MORPHEUS;Initial Catalog=AOR;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" />
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear/>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear/>
<add name="SimpleMembershipProvider"
type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"
enablePasswordReset="true" />
</providers>
</membership>
</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 name="AR_WCF_Library.Service1">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8733/Design_Time_Addresses/AR_WCF_Library/Service1/" />
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address="" binding="wsHttpBinding" contract="AR_WCF_Library.IService1">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<!-- 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>
<!-- 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>
</system.serviceModel>
</configuration>
Add the following to the Web.config of whatever hosts your WCF service:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>