I have a WCF service in which i have a method which return any string.
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(Method="Get", UriTemplate="api/GetData/{name}", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string GetData(string name);
[OperationContract]
[WebInvoke(Method = "Post", UriTemplate = "api/PutData", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
string PutData(string name);
}
When i hit service URL(http://localhost:56075/Service.svc/api/GetData/gt). it display me error "Method Not Allowed" Can you please tell me what is the problem..
And web config is as below :
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="Hello">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="Ajax.Service" behaviorConfiguration="Hello" >
<endpoint address="http://localhost:56075/Service.svc" binding="webHttpBinding" contract="Ajax.IService" behaviorConfiguration="webHttp"></endpoint>
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false"/>
</system.serviceModel>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Change line:
[WebInvoke(Method="Get", UriTemplate="api/GetData/{name}", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
to
[WebInvoke(Method="Get", UriTemplate="api/GetData?name={name}", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
and try again.
Related
I have a web service I have created and I am calling a method inside it and logging to a text file. It seems to be re-starting this method for an infinite number of times as it keeps logging the same line. I suspect it could be something in my config file that is wrong, can someone veryfy the bindings etc pls?
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
</appSettings>
<system.web>
<customErrors mode="Off"/>
<compilation targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
</system.web>
<system.serviceModel>
<services>
<service name="TLS_Service.Service1">
<endpoint address="" binding="webHttpBinding" contract="TLS_Service.IService1" behaviorConfiguration="webBehavior" />
</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>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</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>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.SharePoint.Client" publicKeyToken="71e9bce111e9429c" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-14.0.0.0" newVersion="14.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.SharePoint.Client.Runtime" publicKeyToken="71e9bce111e9429c" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-14.0.0.0" newVersion="14.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
The issue here seemed to be: lack of RAM on the server / too many ExecuteQuery requests in the Web Service Code.
I have 3 project in my solution. First project is asp.net mvc(as client app) and other one is WCF service application and last one is workflow activity library. I added WCF service reference to workflow project and workflow project reference added to asp.net mvc. When I used wcf service in activity and start workflow from asp.net mvc I get this error:
Could not find endpoint element with name BasicHttpBinding_IService
and contract IService 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 name
could be found in the client element.
This my workflow activity library app.config file content:
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:30717/Service1.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService1" contract="Service1.IService1"
name="BasicHttpBinding_IService1" />
</client>
</system.serviceModel>
</configuration>
And this is my wcf project web.config file content:
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpBinding" scheme="http" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
And this is my asp.net mvc web.config file content:
<configuration>
<appSettings>
<add key="webpages:Version" value="3.0.0.0"/>
<add key="webpages:Enabled" value="false"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:30717/Service1.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceTest.IService1"
name="BasicHttpBinding_IService1" />
</client>
</system.serviceModel>
</configuration>
And this is my code for run workflow in asp.net mvc controller:
wf.Activity1 mm = new wf.Activity1();//wf is reference added from workflow project
mm.arg1 = "12".ToString() ;
IDictionary<string, object> res = WorkflowInvoker.Invoke(mm);
ViewBag.res = res["arg2"].ToString();
I googled for a day and unfortunately I didn't get result. Thanks for your guides.
Edit:
This is my project for more help.
Remove the '1' from both contract and name attributes in the workflow config file.
The BasicHttpBinding_IService class generated by VS, when instantiated, it looks up on config for some suitable endpoint that match 2 conditions:
has the name of the class (BasicHttpBinding_IService, if nothing is passed to the constructor). Namespace should be indicate too. In this, the name of the end point should be .BasicHttpBinding_IService
has a contract supported by the class.
To prevent a further error, you should check the name of svc file, the name ends with '1' too. Binding configuration is ok since it exists on the binding section with the exactly same name.
Here a simplified version of the config:
<configuration>
<system.serviceModel>
<client>
<endpoint address="http://localhost:30717/Service.svc" binding="basicHttpBinding" contract="Service1.Service" name="<namespace>.BasicHttpBinding_IService" />
</client>
</system.serviceModel>
Also you can use Visual Studio WFC Service configuration tool (shortcut on tools menu), to edit config files of either clients and services.
the error message is quite correct: you don't have any service endpoints configured in your WCF Services Web.config
add a services node and configure the endpoint like this:
....
<system.serviceModel>
<services>
<service name="MyService">
<endpoint address="" binding="basicHttpBinding" contract="Service1.IService1" />
</service>
</services>
<behaviors>
....
We have an azure cloud service with a WCF installed as web role. The service connects to an azure db online using entity framework. The service is consumed by a WPF Client which use a corporate proxy to connect to the web.
Sometimes the client receive the error: " Server is too busy." , and the inner exception is "HTTP 503 - Service Unavailable".
To investigate this error i tried to connect on the cloud service's VM through remote desktop:
Event Viewer:No sign of application pool crash or errors both in "Application" and in "System" sections.
FREB Logs(with rule activated): Nothing logged.
HTTPerr log:No Trace of the failed requests.
I have activated WCF internal TraceLog. The log correctly trace information but there aren't exceptions or errors logged.
On IIS i have changed:
Application pool from "ondemand" to "always running"
Queue limit
Disabled rapid fail protection ( just for test)
Changed Application pool identity
I also added Telemetry to WCF to log all Exception and some trace of requests.
Nothing has helped, the error continue to appears randomly.
Today i have installed WireShark on the server hosting the WCF and captured inbound traffic.
Even there no sign of failed requests with response code != 200, all the requests are "http1.1 200 OK."
Some days ago i worked from home and used the WPF Client a lot(without using the proxy) and the error never showed up.
Could be related to the corporate proxy we use at work ?
Below the client and WCF Configs:
WPF client config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
</configSections>
<appSettings>
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
</connectionStrings>
</entityFramework>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<bindings>
<customBinding>
<binding name="largedata" closeTimeout="00:21:00" openTimeout="00:20:00" receiveTimeout="00:20:00" sendTimeout="00:20:00">
<security authenticationMode="UserNameOverTransport" messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" allowInsecureTransport="true" />
<binaryMessageEncoding maxReadPoolSize="2147483647" maxWritePoolSize="2147483647" compressionFormat="GZip">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binaryMessageEncoding>
<httpTransport bypassProxyOnLocal="True"
authenticationScheme="Basic"
useDefaultWebProxy="True"
proxyAuthenticationScheme="Basic"
keepAliveEnabled="True"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647" />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="http://wcfadress/Data.svc" binding="customBinding" bindingConfiguration="largedata" contract="DataService.DataService" name="largedata" />
</client>
</system.serviceModel>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.Edm" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.Services.Client" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.OData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<proxy proxyaddress="http://proxyadress" ></proxy>
</defaultProxy>
<settings>
<servicePointManager expect100Continue="false" />
</settings>
</system.net>
<system.web>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" />
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" />
</providers>
</roleManager>
</system.web>
</configuration>
WCF 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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.diagnostics>
<trace>
<listeners>
<add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics">
<filter type="" />
</add>
</listeners>
</trace>
<sources>
<source name="System.ServiceModel" switchValue="Critical, Error, Warning" propagateActivity="true">
<listeners>
<add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="c:\temp\TracesWCF.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
<connectionStrings>
<add name="Clio" providerName="System.Data.EntityClient" connectionString="metadata=res://*/DataMadel.csdl|res://*/DataMadel.ssdl|res://*/DataMadel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=*****;Initial Catalog=*****;Language=Italian;Integrated Security=False;*****;Password=*****;Connection Timeout=600;MultipleActiveResultSets=True;Encrypt=True;Min Pool Size=20;Max Pool Size=50;TrustServerCertificate=False"" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" maxRequestLength="202400" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Extensibility.Web.RequestTracking.WebRequestTrackingModule, Microsoft.ApplicationInsights.Extensibility.Web" />
</httpModules>
</system.web>
<system.serviceModel>
<diagnostics>
<messageLogging
logEntireMessage="true"
logMalformedMessages="false"
logMessagesAtServiceLevel="true"
logMessagesAtTransportLevel="true"
maxMessagesToLog="400"
maxSizeOfMessageToLog="6000"/>
</diagnostics>
<bindings>
<customBinding>
<binding name="largedata" closeTimeout="00:21:00" openTimeout="00:20:00" receiveTimeout="00:20:00" sendTimeout="00:50:00">
<security authenticationMode="UserNameOverTransport" messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" allowInsecureTransport="true" />
<binaryMessageEncoding maxReadPoolSize="2147483647" maxWritePoolSize="2147483647" compressionFormat="GZip">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binaryMessageEncoding>
<httpTransport maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
</binding>
</customBinding>
</bindings>
<services>
<service name="ArchivioStorico.Service.DataService" behaviorConfiguration="Auth">
<endpoint address="" binding="customBinding" bindingConfiguration="largedata" contract="ArchivioStorico.Service.DataService" />
<endpoint address="basicHttp" binding="basicHttpBinding" contract="ArchivioStorico.Service.DataService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Auth">
<!-- 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" />
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<serviceThrottling maxConcurrentCalls="1300" maxConcurrentSessions="1300" maxConcurrentInstances="1300"></serviceThrottling>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ArchivioStorico.Service.CustomValidator.CustomUserNameValidator, App_Code" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
<add binding="basicHttpBinding" scheme="http" />
<add binding="webHttpBinding" scheme="http" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Extensibility.Web.RequestTracking.WebRequestTrackingModule, Microsoft.ApplicationInsights.Extensibility.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" />
<security>
<requestFiltering>
<!--Increase 'maxAllowedContentLength' to needed value: 100mb (value is in bytes)-->
<requestLimits maxAllowedContentLength="204857600" />
</requestFiltering>
</security>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.Edm" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.Services.Client" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.OData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.net>
<settings>
<servicePointManager expect100Continue="false" />
</settings>
</system.net>
</configuration>
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.
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 );
});