I am trying to hit an HTTPS REST SERVICE hosted on Windows Server from a website hosted on Unix Server but I am getting 405 Method Not Allowed error.
Exception I am getting on browser console is::
OPTIONS
https://auth.syrasoft.com/10.0.0.101/authservice.svc/rest/r_PerformLogin
XMLHttpRequest cannot load
https://auth.syrasoft.com/10.0.0.101/authservice.svc/rest/r_PerformLogin.
Response for preflight has invalid HTTP status code 405
My Client Code which is trying to access REST service is:
createCORSRequest: function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
},
doSignIn: function(event) {
console.log('inside sign in');
event.preventDefault();
$('#ErrMsg').hide(); // Hide any errors on a new submit
console.log('Logging in... ');
var url = 'https://auth.syrasoft.com/10.0.0.101/authservice.svc/rest/r_PerformLogin';
var method = 'POST';
var formValues = {
AccountID: 28462,
CurrentVersion: "10.0.0.103",
GoogleRedirect: null,
GoogleToken: null,
GroupID: 0,
Method: 2,
PC_Name: "DEV7",
Password: [97, 136, 201, 199, 60, 1, 89, 216, 184, 191, 82, 1, 114, 252, 127, 16, 0, 184, 64, 9, 82, 84, 81, 147, 12, 83, 100, 38, 197, 209, 252, 151],
Source: 0,
UserName: "mikeo"
};
var xhr = this.createCORSRequest(method, url);
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");
xhr.setRequestHeader("Accept","application/json");
xhr.onload = function() {
console.log('success');
var data = xhr.responseText;
if (data) {
var json = jQuery.parseJSON(data);
console.log(json);
app.navigate("home", {
trigger: true
});
}
};
xhr.onerror = function() {
console.log('error');
var data = xhr.responseText;
if (data) {
var json = jQuery.parseJSON(data);
$('#ErrMsg').text(json.error.text).show();
}
};
xhr.send(JSON.stringify(formValues));
}
Configuration on REST Server side is:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="EnableDebugLogging" value="true" />
<add key="LogFileName" value="AuthenticationService.txt" />
</appSettings>
<system.web>
<customErrors mode="Off"/>
<compilation strict="false" explicit="true" targetFramework="4.0">
<assemblies>
<add assembly="MySql.Data, Version=6.9.5.0, Culture=neutral, PublicKeyToken=C5687FC88969C44D" />
</assemblies>
</compilation>
<pages>
<namespaces>
<add namespace="System.Runtime.Serialization" />
<add namespace="System.ServiceModel" />
<add namespace="System.ServiceModel.Web" />
</namespaces>
</pages>
</system.web>
<system.serviceModel>
<client>
<endpoint address="http://localhost:64331/AutoUpdate.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IVersionCheck" contract="AutoUpdateService.IVersionCheck" name="BasicHttpBinding_IVersionCheck" />
</client>
<services>
<service name="AuthenticationService">
<endpoint address="" binding="wsHttpBinding" name="wb" contract="IAuthenticationService" bindingConfiguration="wb">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint name="restful" address="rest" binding="webHttpBinding" contract="IRESTfulAuth" bindingConfiguration="bw" behaviorConfiguration="web"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost/" />
</baseAddresses>
</host>
</service>
</services>
<!--Binding Settings-->
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IVersionCheck" />
</basicHttpBinding>
<wsHttpBinding>
<binding name="wb" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00">
<security mode="Transport">
<transport clientCredentialType="None" />
</security>
</binding>
</wsHttpBinding>
<webHttpBinding>
<binding name="bw" receiveTimeout="00:10:00" sendTimeout="00:10:00" openTimeout="00:10:00" closeTimeout="00:10:00">
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment 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="false" />
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Headers" value="Content-Type,Accept,X-Requested-With" />
<add name="Access-Control-Allow-Origin" value="http://syrasoftconnect.com" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
The thing here is when I mock the REST Service through SOAP UI, I am perfectly able to call it from the website but not when it is hosted on the Windows Server. I believe there could be some problem with the server configuration but I am not able to pin point it. I have tried almost all the solutions available on stackoverflow related to the same issue but no luck.
Do you guys see anything wrong in my code or server configuration?
Related
Hi I'm posting to a wcf service from javascript. I can post a single parameter (string, blob, int) fine, but when I try to put the data in a class I get a 400 Bad Request error. I've tried both Bare and Wrapped for my BodyStyle, but get the same error for each. Any ideas what could be happening?
Thanks
Pete
C# Data Contract:
[DataContract]
public class TestData
{
[DataMember]
public string SubmissionID { get; set; }
}
C# Interface:
[OperationContract(Name = "Upload")]
[DataContractFormat]
[WebInvoke(Method = "POST",
UriTemplate = "Upload/",
BodyStyle = WebMessageBodyStyle.Wrapped,//Bare gives same error
ResponseFormat = WebMessageFormat.Json)]
String Upload(TestData ps);
C# Service Method:
public String Upload(TestData ps)
{
....
return "Submission Complete";
}
Javascript call:
var TestData = {SubmissionID: "1" };
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:59070/WCFUploader.svc/Upload/', true);
xhr.send(TestData);//400 Bad Request
C# Web Config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1"/>
</system.web>
<system.serviceModel>
<services>
<service name="PhotoUploadServiceTest.WCFUploader" behaviorConfiguration="defaultServiceBehavior">
<endpoint address="" binding="webHttpBinding" behaviorConfiguration="defaultEndpointBehavior"
contract="PhotoUploadServiceTest.IWCFUploader" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
transferMode="Streamed"
sendTimeout="00:05:00">
<readerQuotas maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647"/>
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="defaultEndpointBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="defaultServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</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>
The problem was in my javascript call. I needed to set the content of the request header to "application/json" and needed to create a String serial of the object before I sent it -- used dojo.toJson from the dojo library:
var TestData = {SubmissionID: "1" };
xhr.setRequestHeader("Content-type", "application/json");
var xhr = new XMLHttpRequest();
xhr.open('POST',
'http://localhost:59070/WCFUploader.svc/Upload/', true);
xhr.send(dojo.toJson(TestData));//this worked!!
I created a wcf self service host
I can access it , and see it's wsdl
but when trying to add the /js extension to the path I get 405 error.
I cannot understand why, while doing the same with a asp.net web applicaton it worked ok.
wcf class :
namespace A
{
[ServiceBehavior(IncludeExceptionDetailInFaults=true)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Hello : IHello
{
public string SayHi()
{
return "Hiush !";
}
}
}
wcf interface:
namespace A
{
[ServiceContract]
public interface IHello
{
[OperationContract]
string SayHi();
}
}
wcf svc file:
<%# ServiceHost Language="C#" Debug="true" Service="A.Hello" %>
the self service host:
namespace SelfServiceHost
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost helloHost = new ServiceHost(typeof(A.Hello)))
{
helloHost.Open();
Console.WriteLine("HelloHost started # " + DateTime.Now);
Console.ReadKey();
}
}
}
}
self service host app.config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true"/>
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="true" hostNameComparisonMode="StrongWildcard"
maxBufferSize="524288" maxBufferPoolSize="524288" maxReceivedMessageSize="524288"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="524288" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<!--<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>-->
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="A.Hello">
<endpoint address="PINCalc" behaviorConfiguration="AAA"
binding="webHttpBinding" contract="A.IHello">
<!--<identity>
<dns value="localhost"/>
</identity>-->
</endpoint>
<host>
<baseAddresses>
<add baseAddress="http://localhost:3020/Hello.svc"/>
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="True"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="AAA">
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
Alright I really hate it when it has this error in the console. And I know that stackoverflow is flooded with these types of questions. However, I've done the research and I have CORS enabled in my Web API 2 web service and I'm still getting this error.
This is my Web API 2 code:
namespace WebApi.App.Controllers
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ServiceController : ApiController
{
[HttpGet]
[Route("GetData")]
public IHttpActionResult GetEmpData(DATAvars theDATA)
{
return Ok("WORKED! " + theDATA);
}
[HttpPost]
[Route("PostData")]
public IHttpActionResult PostEmpData(DATAvars theDATA)
{
return Ok("WORKED! " + theDATA.theID);
}
}
public class DATAvars
{
public string theID { get; set; }
public string empImg { get; set; }
}
}
AND
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
AND
namespace WebApi.App
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.MapHttpAttributeRoutes();
config.EnableCors();
}
}
}
AND
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS" )
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods" , "GET, POST" );
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers" , "Content-Type, Accept" );
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
}
Then for my AJAX call code (which is being hosted on another domain):
$.ajax({
type: "POST",
crossDomain: true,
url: "http://dev-blahblah/newWS/PostData",
beforeSend: function (xhrObj) {
xhrObj.setRequestHeader("Content-Type", "application/json");
},
data: {
theID: "2135648792",
empImg: "false"
},
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
}
});
And this is the error in the console:
The Console Network says:
Failed to load resource: the server responded with a status of 404 (Not Found)
index.html:1 XMLHttpRequest cannot load http://dev-blahblah/newWS/PostData. Response for preflight has invalid HTTP status code 404
And now this is the SAME request but in POSTMAN:
I've spent DAYS trying to figure this out and endless googleing to find examples, I have, but seems like all the examples do not work.
I would be very grateful for someone to let me know what I need to do in order to get this working with JQUERY AJAX.
-Running it on the same domain in CHROME = WORKS
-Running it on a different domain in CHROME = DOES NOT WORK
-Running it on the same domain in IE = WORKS
-Running it on a different domain in IE = WORKS
Used the following config section in my web API web.config file to avoid the 404 error.
<handlers>
<remove name="WebDAV"/>
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<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" />
<add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" requireAccess="None" responseBufferLimit="4194304" />
</handlers>
Removing WebDAV did not work for me as there might be a global policy on my server. This, however, cut it:
<system.webServer>
<security>
<requestFiltering>
<verbs applyToWebDAV="false">
<add verb="DELETE" allowed="true" />
<add verb="PUT" allowed="true" />
<add verb="OPTIONS" allowed="true" />
</verbs>
</requestFiltering>
</security>
</system.webServer>
It was <add verb="OPTIONS" allowed="true" /> that made the difference.
I am having a WCF service to read file content and i am calling it on my webpage using JavaScript and getting the content as response.
Now what i have to do is instead of reading its content i have to download this file from server to the client system,any idea how to do get a file from server using wcf ?
WCF:-
public Stream getFileFromPath(string filepath)
{
String[] filename=filepath.Split('\\');
WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
if(File.Exists(filepath)
{
String headerInfo = "attachment; filename=" + filename[filename.Length - 1];
WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = headerInfo;
return File.OpenRead(filepath);
}
else
{
String headerInfo = "attachment; filename=" + "error.txt";
WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = headerInfo;
string errortext="file not found";
byte[] byteArray = Encoding.ASCII.GetBytes(errortext);
MemoryStream stream = new MemoryStream(byteArray);
return stream;
}
}
web.config:-
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="MyWcfRestService.WebHttp" maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
transferMode="Streamed"
sendTimeout="00:05:00">
<readerQuotas maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647"/>
<security mode="None" />
</binding>
</webHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="MyWcfRestService.FileUploadServBehavior" name="MyWcfRestService.FileUploadServ">
<endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" bindingConfiguration="MyWcfRestService.WebHttp" contract="MyWcfRestService.IFileUploadServ">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp helpEnabled=”true”/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="MyWcfRestService.FileUploadServBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
JavaScript:-
function downloadfile(filepath)
{
var url="https://abc/service.svc/getfilestream?v="+filepath;
window.open(url,"windowname","width:400,height:300");
}
I have 2 projects from which I need to call WCF services.
I have a problem calling services from one of them.
Therefore I made a simple service which is identical in both projects called Test1.
The SVC, ISVC and the Web.Config files are identical.
Any ideas what else can influance and be the reason why one project is working file and the other return a Bad request error.
I am working with Visual studio 2012.
Following is my code:
SVC file:
namespace Proj1.Web
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Proj1SVC : IProj1SVC
{
public string Test1()
{
return "Project 1";
}
}
}
ISVC file:
namespace Proj1.Web
{
[ServiceContract]
public interface IProj1SVC
{
[OperationContract]
string Test1();
}
}
Web.Config file:
<?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>
<connectionStrings>
<add name="Proj1dbConnectionString" connectionString="Data Source=Proj1Comp\SQLEXPRESS;Initial Catalog=Proj1dbKK;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<roleManager enabled="true"/>
<compilation debug="true" targetFramework="4.0">
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<!-- <authentication mode="Windows"/> -->
<authentication mode="Forms">
<!-- The name, protection, and path attributes must match
exactly in each Web.config file. -->
<forms loginUrl="login.aspx" name=".ASPXFORMSAUTH" protection="All" path="/" domain="kk.Proj1.com" timeout="600"/>
</authentication>
<!-- Validation and decryption keys must exactly match and cannot
be set to "AutoGenerate". The validation and decryption
algorithms must also be the same. -->
<machineKey validationKey="SomeValidationKeyInHex" decryptionKey="SomeDecryptionKeyInHex" validation="SAA1"/>
<authorization>
<allow roles="administrators"/>
<allow users="?" />
</authorization>
<!--
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="3.5" clientIDMode="AutoID"/>
</system.web>
<!-- Added for server side authentication data to be available in the WCF service -->
<!-- STX -->
<system.web.extensions>
<scripting>
<webServices>
<authenticationService enabled="true" requireSSL="false"/>
</webServices>
</scripting>
</system.web.extensions>
<!-- ETX -->
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"/>
<diagnostics>
<messageLogging
logEntireMessage="true"
logMalformedMessages="false"
logMessagesAtServiceLevel="true"
logMessagesAtTransportLevel="false"
maxMessagesToLog="3000"
maxSizeOfMessageToLog="2000"/>
</diagnostics>
</system.serviceModel>
</configuration>
you need to specify attributes at operation level in the service contract file for each method or operation. To do this, decorate the method with WebInvoke, which marks a service operation as one that responds to HTTP requests other than GET. Accordingly, your operational level code in the contract file will be as follows:
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
string Test1(string Id);
You need to change the default configuration created by Visual Studio in Web.Config file for WCF services, so that it works with the HTTP protocol request send by jQuery client code.
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="Service">
<endpoint address="" binding="webHttpBinding"
contract="IService" behaviorConfiguration="EndpBehavior"/>
</service>
</services>
</system.serviceModel>
Call ur service using jQuery.ajax()
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function(msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
function ServiceFailed(result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
Type = null;
varUrl = null;
Data = null;
ContentType = null;
DataType = null;
ProcessData = null;
}