I have wcf services on http://testwcfgrid.atic-solutions.com/ where everything is working fine.
I want to consume that service in another application with jQuery.ajax but without success.
My web.config is:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="origin, content-type, accept" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="ProductsAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ProductsAspNetAjaxBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint name="" crossDomainScriptAccessEnabled="true"/>
</webScriptEndpoint>
</standardEndpoints>
<services>
<service name="Products" behaviorConfiguration="ProductsAspNetAjaxBehavior">
<endpoint address="" behaviorConfiguration="ProductsAspNetAjaxBehavior" binding="webHttpBinding" contract="Products" />
</service>
</services>
</system.serviceModel>
my wcf services for read and create:
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
public DataSourceResult Read(int skip, int take, IEnumerable<Sort> sort, Filter filter)
{
VoziloMassive table = new VoziloMassive();
return table.GetVehicles().AsQueryable().Select(x => new VoziloViewModel
{
Id = x.Id,
Timestamp = x.Timestamp,
Marka = x.Marka,
Registracija = x.Registracija,
Vrsta = x.Vrsta,
Flag = x.Flag
}).ToDataSourceResult(take, skip, sort, filter);
}
[OperationContract]
public IEnumerable<VoziloViewModel> Create(IEnumerable<VoziloViewModel> vehicles)
{
var result = new List<VoziloViewModel>();
foreach (var vehicleViewModel in vehicles)
{
// Create a new Product entity and set its properties from productViewModel
var vehicle = new VoziloViewModel
{
Marka = vehicleViewModel.Marka,
Registracija = vehicleViewModel.Registracija
};
// store the product in the result
result.Add(vehicle);
// Add the entity
VoziloMassive table = new VoziloMassive();
table.AddVehicle(vehicle);
}
// Return the inserted products - the Kendo Grid needs their ProductID which is generated by SQL server during insertion
return result.Select(x => new VoziloViewModel
{
Id = x.Id,
Timestamp = x.Timestamp,
Marka = x.Marka,
Registracija = x.Registracija,
Vrsta = x.Vrsta,
Flag = x.Flag
})
.ToList();
}
my .ajax call:
$.ajax({
url: "http://testwcfgrid.atic-solutions.com/Products.svc/Read",
dataType: "jsonp",
success: function (result) {
// notify the data source that the request succeeded
options.success(result);
},
error: function (result) {
// notify the data source that the request failed
options.error(result);
}
});
and this is response:
http://prntscr.com/3xxdjw
What am I missing here? I tried everything... I am using telerik kendo controls and I was following their examples.
Thanks
Regarding my previous comment - doesn't look like the url is valid to call the Read method.
I think this is because you haven't specified the UriTemplate definition for each of the method calls.
Also note that the Method type is not specified.
Update your method as follows:
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "Read")]
public DataSourceResult Read(int skip, int take, IEnumerable<Sort> sort, Filter filter)
Related
How can I receive multipart form data in a WCF Service? I have uploaded it using the phone gap file transfer plugin upload function.
Below are the two functions that I'm trying to call:
///<summary>
///Method for file upload
///</summary>
[OperationContract]
[WebInvoke(
Method = "POST",
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "Upload")]
string Upload(Stream data);
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "UploadImage")]
string UploadImage();
// TODO: Add your service operations here
I successfully hit the UploadImage function but I don't know how to read a file from the uploaded data.
When I try
HttpPostedFile file = HttpContext.Current.Request.Files["recFile"];
I get the error:
HttpContext.Current.Request.Files 'HttpContext.Current.Request.Files' threw an exception of type 'System.Web.HttpException' System.Web.HttpFileCollection {System.Web.HttpException}
base {"This method or property is not supported after HttpRequest.GetBufferlessInputStream has been invoked."}
This is my web.config file:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<customErrors mode="RemoteOnly"/>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="CacheFor10Seconds" duration="10"
varyByParam="none" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
<httpRuntime maxRequestLength="2000000000"/>
</system.web>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
</appSettings>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP"
crossDomainScriptAccessEnabled="true" maxBufferSize="2000000000"
maxReceivedMessageSize="2000000000"
transferMode="Streamed" />
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="Service.Service1">
<endpoint name="mexHttpBinding"
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"
/>
<endpoint address="" behaviorConfiguration="webHttpBehavior"
binding="webHttpBinding"
bindingConfiguration="webHttpBindingWithJsonP"
contract="Service.IService1" />
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
I got the problem it with the Wcf version targetFramework="4.5" issue ,
you have to add below code in web config than the issue get resolve:
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
<add key="wcf:serviceHostingEnvironment:useClassicReadEntityBodyMode" value="true" />
</appSettings>
my all the other web Config that i post already here is working fine below is the updated web config setting
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<customErrors mode="RemoteOnly"/>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="CacheFor10Seconds" duration="10"
varyByParam="none" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
<httpRuntime maxRequestLength="2000000000"/>
</system.web>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
<add key="wcf:serviceHostingEnvironment:useClassicReadEntityBodyMode" value="true" />
</appSettings>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP"
crossDomainScriptAccessEnabled="true" maxBufferSize="2000000000"
maxReceivedMessageSize="2000000000"
transferMode="Streamed" />
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="Service.Service1">
<endpoint name="mexHttpBinding"
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"
/>
<endpoint address="" behaviorConfiguration="webHttpBehavior"
binding="webHttpBinding"
bindingConfiguration="webHttpBindingWithJsonP"
contract="Service.IService1" />
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
This is my Service and IService Code:
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "UploadImage")]
string UploadImage();
#region
///<summary>
///Metohd to upload image.
///</summary>
public string UploadImage()
{
string JsonString = string.Empty;
JsonString = AppDomain.CurrentDomain.BaseDirectory;
try {
HttpPostedFile file = HttpContext.Current.Request.Files[0];
;
if (file == null)
{
RC.ErrorLog.LogFileWrite("<Exception>File is null</Exception>" + JsonString);
return JsonString;
}
string targetFilePath = AppDomain.CurrentDomain.BaseDirectory + #"Images\Upload" + Guid.NewGuid() + file.FileName.ToString();
file.SaveAs(targetFilePath);
return file.FileName.ToString();
}
catch(Exception e)
{
string errorMessage = RC.ErrorLog.CreateErrorMessage(e);
RC.ErrorLog.LogFileWrite(errorMessage+JsonString);
return JsonString;
}
}
#endregion
And below is my JqueryMobile code for PhoneGap
// A button will call this function
//
function captureImage() {
// Launch device camera application,
// allowing user to capture up to 2 images
debugger;
navigator.device.capture.captureImage(captureSuccess, captureError, { limit: 2 });
}
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
// Called if something bad happens.
//
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
function uploadFile(mediaFile) {
var ft = new FileTransfer();
path = mediaFile.fullPath;
name = mediaFile.name;
debugger;
// below varible contain the Server url name that i created by joining defenrent 3 var of //my application
var objUrl = _ServicesUrl._SecondServicePath + _ServicePage._BaseServicePage + _WcfFunctionUrl._ImageUpload;
alert("uploadImage");
ft.upload(path,
objUrl,
function (result) {
alert('Upload success: ' + result.responseCode);
alert(result.bytesSent + ' bytes sent');
debugger;
var abc = JSON.parse(result.Upload);
alert(abc);
},
function (error) {
alert('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}
Hope the answer will help the community.
im using the thinktecture identityserver Security Token Service im trying to set up a scenario where I have a client using a WCF service. I'm stuck at a point where I get next error:
MessageSecurityException
An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.
InnerException
At least one security token in the message could not be validated.
I've setup the STS on a win2008 server and all working correct its already working with an MVC site. But with a wcf service I cant get it to work. I'm using bearerkey as SecurityKeyType. I do get a token in the client app function RequestToken(). Here is my wcf service config:
<system.serviceModel>
<services>
<service name="ClaimWcfService.Service1">
<endpoint address="ClaimWcfService" binding="ws2007FederationHttpBinding" bindingConfiguration="" contract="ClaimWcfService.IService1" />
<host>
<baseAddresses>
<add baseAddress="https://anno99-pc/"/>
</baseAddresses>
</host>
</service>
</services>
<bindings>
<ws2007FederationHttpBinding>
<binding name="">
<security mode="TransportWithMessageCredential">
<message establishSecurityContext="false" issuedKeyType="BearerKey">
<issuerMetadata address="https://serveradress/Idsrv/issue/wstrust/mex" />
</message>
</security>
</binding>
</ws2007FederationHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceAuthorization principalPermissionMode="Always" />
<serviceCredentials useIdentityConfiguration="true">
<serviceCertificate findValue="ANNO99-PC" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add scheme="http" binding="ws2007FederationHttpBinding" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<!-- Config STS -->
<system.identityModel>
<identityConfiguration>
<audienceUris>
<add value="https://anno99-pc/ClaimWcfService/Service1.svc" />
</audienceUris>
<!--Commented by Identity and Access VS Package-->
<certificateValidation certificateValidationMode="None" />
<issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry">
<authority name="http://identityserver.v2.wkp.com/trust/wkp">
<keys>
<add thumbprint="A540AD5B90B8459E919B39301B89F279A3AAEADB" />
</keys>
<validIssuers>
<add name="http://identityserver.v2.wkp.com/trust/wkp" />
</validIssuers>
</authority>
</issuerNameRegistry>
</identityConfiguration>
</system.identityModel>
This is the client: It is just a console app.
static void Main(string[] args)
{
var token = RequestToken();
CallService(token);
}
static string _idsrvEndpoint = "https://serveradress/Idsrv/issue/wstrust/mixed/username";
static string _realm = "https://anno99-pc/ClaimWcfService/";
private static void CallService(SecurityToken token)
{
var serviceEndpoint = "https://anno99-pc/ClaimWcfService/Service1.svc";
var binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential);
binding.Security.Message.EstablishSecurityContext = false;
binding.Security.Message.IssuedKeyType = SecurityKeyType.BearerKey;
var factory = new ChannelFactory<IService1>(binding,
new EndpointAddress(serviceEndpoint));
factory.Credentials.SupportInteractive = false;
factory.Credentials.UseIdentityConfiguration = true;
var channel = factory.CreateChannelWithIssuedToken(token);
var data = channel.GetData(1);
}
private static SecurityToken RequestToken()
{
var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential);
var credentials = new ClientCredentials();
credentials.UserName.UserName = "username";
credentials.UserName.Password = "password";
return WSTrustClient.Issue(
new EndpointAddress(_idsrvEndpoint),
new EndpointAddress(_realm),
binding,
credentials);
}
If anyone could help me, that would be great.
After some googling and trying, I got it to work. I had to change these parts of the configuration.
<services>
<service name="ClaimWcfService.Service1">
<endpoint address="" binding="ws2007FederationHttpBinding" bindingConfiguration="" contract="ClaimWcfService.IService1" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceAuthorization principalPermissionMode="Always" />
<serviceCredentials useIdentityConfiguration="true">
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<system.identityModel>
<identityConfiguration saveBootstrapContext="true">
<audienceUris>
<add value="https://anno99-pc/ClaimWcfService/" />
</audienceUris>
<certificateValidation certificateValidationMode="None" />
<issuerNameRegistry type="System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<trustedIssuers>
<add thumbprint="A540AD5B90B8459E919B39301B89F279A3AAEADB"
name="idsrv" />
</trustedIssuers>
</issuerNameRegistry>
</identityConfiguration>
</system.identityModel>
I hope this helps someone
Based on the MSDN documentation I have created a custom UserNameSecurityTokenHandler and put in the CanValidateToken override and ValidateToken override. I thought I had configured the WCF web service to use the custom handler but the ValdiateToken never gets called. Here is the custom token handler:
public class CustomUserNameSecurityTokenHandler : UserNameSecurityTokenHandler
{
public override bool CanValidateToken
{
get { return true; }
}
public override ReadOnlyCollection<ClaimsIdentity> ValidateToken(SecurityToken token)
{
System.Diagnostics.Debugger.Launch();
if (token == null)
{
throw new ArgumentNullException();
}
var userNameToken = token as UserNameSecurityToken;
if (userNameToken == null)
{
throw new SecurityTokenException("Invalid token");
}
if ( userNameToken.UserName != userNameToken.Password )
{
throw new SecurityTokenException("Invalid username or password.");
}
var claims = new List<Claim>
{
new Claim(System.IdentityModel.Claims.ClaimTypes.Name, userNameToken.UserName),
new Claim(
"http://schemas.microsoft.com/ws/2008/06/identity/claims/ClaimTypes.AuthenticationInstant",
XmlConvert.ToString(DateTime.UtcNow, "yyyy-MM-ddTHH:mm:ss.fffZ"),
"http://www.w3.org/2001/XMLSchema#dateTime")
};
return new ReadOnlyCollection<ClaimsIdentity>(new List<ClaimsIdentity> {new ClaimsIdentity(claims, "Password")});
}
}
The debugger does not launch. The client code always fails when I call it.
Here is my WCF web.config entries for the site:
<configSections>
<section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<services>
<service name="WcfUserName.Service1">
<endpoint address="Service1.svc" binding="netHttpBinding"
contract="WcfUserName.IService1" />
<host>
<baseAddresses>
<add baseAddress="https://localhost/WcfUserName" />
</baseAddresses>
</host>
</service>
</services>
<bindings>
<netHttpBinding>
<binding>
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName" />
</security>
</binding>
</netHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceCredentials useIdentityConfiguration="true" />
<serviceAuthorization principalPermissionMode="Always"/>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="netHttpBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
<system.identityModel>
<identityConfiguration name="identconfig">
<securityTokenHandlers>
<remove type="System.IdentityModel.Tokens.WindowsUserNameSecurityTokenHandler, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add type="WcfUserName.Security.CustomUserNameSecurityTokenHandler, WcfUserName"/>
</securityTokenHandlers>
</identityConfiguration>
</system.identityModel>
I assume something is wrong with my configuration but cannot tell what it is. Any ideas?
AFAIK, you need to configure this correctly in web.config. This means you need to add you securitytokenhandler, but also remove the default username password handler. So you need to either <remove > the previous handler, or start over and <clear> the collection of securitytokenhandlers in the configuration file.
I have a WCF REST service (.NET4).
It works fine (browser, ajax call) for calls without parameters but I cannot get it to work with parameters. Neither in the browser nor via an ajax call.
My contract:
[OperationContract]
[WebGet(
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "knowledgefields")]
IEnumerable<cKnowledgeField> GetKnowledgeFields();
[OperationContract]
[WebGet(
BodyStyle = WebMessageBodyStyle.Bare,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "knowledgeitems?id={id}")]
IEnumerable<cKnowledgeItem> GetKnowledgeItemsByField(string id);
My web.config
<configuration>
<appSettings/>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</assemblies>
</compilation>
</system.web>
<system.serviceModel>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="Json"/>
</webHttpEndpoint>
</standardEndpoints>
<services>
<service name="ExpertData.expertREST" behaviorConfiguration="META">
<endpoint address="" bindingConfiguration="webHttpBindingWithJsonP" binding="webHttpBinding" contract="ExpertData.IexpertREST"/>
</service>
</services>
<protocolMapping>
<add scheme="http" binding="webHttpBinding"/>
</protocolMapping>
<behaviors>
<serviceBehaviors>
<behavior name="META">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior>
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true"/>
</webHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
<connectionStrings>
<add name="FindAnExpertEntities" connectionString="metadata=res://*/ExpertData.csdl|res://*/ExpertData.ssdl|res://*/ExpertData.msl;provider=System.Data.SqlClient;provider connection string="data source=WIN8ATWORK\SQLEXPRESS;initial catalog=FindAnExpert;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"/>
</connectionStrings>
</configuration>
Ajax call:
function getKnowledgeItems(id) {
return $.ajax({
url: "http://localhost:31634/expertREST.svc/knowledgeitems",
dataType: "jsonp"
data: { "id" : id + "" }
}).then( function( data, textStatus, jqXHR ) {
amplify.publish( "knowledgeItemsdata.updated", data );
});
}
Your AJAX call is passing the ID in the message body, BUT you service expects it as as part of the query string. Change javascript to:
return $.ajax({
url: "http://localhost:31634/expertREST.svc/knowledgeitems"
+ "?id=" + id,
dataType: "jsonp"
}).then( function( data, textStatus, jqXHR ) {
amplify.publish( "knowledgeItemsdata.updated", data );
});
I am trying to set up a WCF Service but I'm having a few problems. The service works and loads the wsdl page when I type in
www.mydomain.com/Service1.svc
However when I use
www.mydomain.com/Service1.svc/
or try to use any of the get methods I get
The resource cannot be found.
Description: HTTP 404.
My web.config file is as follows
<?xml version="1.0"?>
<configuration>
<system.webServer>
<handlers>
<remove name="PageHandlerFactory-ISAPI-4.0"/>
<add name="PageHandlerFactory-ISAPI-4.0" path="*" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<remove name="ASP.NET-ISAPI-4.0-Wildcard"/>
<add name="ASP.NET-ISAPI-4.0-Wildcard"
path="*" verb="GET,HEAD,POST,DEBUG"
modules="IsapiModule"
scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll"
preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<remove name="svc-Integrated-4.0" />
<add name="svc-Integrated-4.0" path="*" verb="*" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
<system.web>
<customErrors mode="Off"/>
<compilation debug="true" targetFramework="4.0">
</compilation>
<httpHandlers>
<remove verb="*" path="*.svc"/>
<add path="*.svc" verb="*" type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" validate="false" />
</httpHandlers>
</system.web>
<system.serviceModel>
<services>
<service name="RestService.Service1" behaviorConfiguration="ServiceBehaviour" >
<endpoint address="" binding="webHttpBinding" contract="RestService.IService1" behaviorConfiguration="web">
</endpoint>
<host>
<baseAddresses>
<add baseAddress="http://mydomain.com/Service1"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour" >
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
The Service.svc file is as follows :
namespace RestService
{
public class Service1 : IService1
{
public bool LoginUser( string Username, string password )
{
return true;
}
}
}
and the IService.cs is as follows:
namespace RestService
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
//BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "login/{username}/{password}")]
bool LoginUser(string username, string password);
}
}
The pipeline mode on the server is "Integrated" if that helps. I'm not sure what IIS version my hosting provider (pipeten) uses but I think it's 7.5 I have a feeling this has something to do with the URL validation however there is no option on my hosting to change this.
Okay turns out it was a simple mistake that I had made, I had missed out the . when adding the handler. Instead of path = "" it should have been path="."
<add name="ASP.NET-ISAPI-4.0-Wildcard"
path=".*" verb="GET,HEAD,POST,DEBUG"
modules="IsapiModule"
scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll"
preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />