I have to make multiple WCF service calls by using jquery to update different areas of the web page after a specified time interval. If I make a single call to the WCF service it works fine, but when there are two or more parallel calls to the WCF service no response is received.
All the service calls are made after some specified time-interval. Following is the code of one of them:
var type = "POST";
var contentType = "application/json; charset=utf-8";
var dataType = "json";
var processData = true;
function LoadData()
{
var url = serviceURL;
var data = '{}';
CallService(url, data, LoadDataSuccess);
}
function LoadDataSuccess(result)
{
if (dataType == "json")
{
//other code...
setTimeout("LoadData()", 5000);
}
}
function CallService(url, data, SuccessMethod)
{
$.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)
{
SuccessMethod(msg);
},
error: ServiceFailed
});
}
function ServiceFailed(result)
{
alert('Service call failed: ' + result.status + '' + result.statusText);
type = null; contentType = null; dataType = null; processData = null;
}
And my wcf service looks like this:
public interface ITestService
{
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
List<Data> GetData();
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
List<Data> GetUser();
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
List<Data> GetCustomer();
}
And the configuration looks like this:
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<behaviors>
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="TestService">
<endpoint address="" binding="webHttpBinding" contract="ITestService" behaviorConfiguration="EndpBehavior"/>
</service>
</services>
</system.serviceModel>
Related
I'm having some difficulties getting SwaggerWCF to load my documentation page, and I'm not sure why. I get no errors, but I also get no Swagger docs either, just a 404 when I visit http://localhost:8733/docs per the endpoint configuration. What am I doing wrong here? I have everything decorated up, using Framework 4.8. Service works fine and the mex and js endpoints will return data, just no swaggerUI.
Here is my App.Config:
<system.serviceModel>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" contentTypeMapper="Microsoft.Samples.WebContentTypeMapper.JsonContentTypeMapper, JsonContentTypeMapper, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</webHttpEndpoint>
</standardEndpoints>
<services>
<service name="AutodeskVaultAPI.VaultWorker">
<endpoint address="" binding="basicHttpBinding" contract="AutodeskVaultAPI.IVaultServices">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<endpoint address="js" behaviorConfiguration="jsonEP" binding="webHttpBinding"
name="jsonEP" contract="AutodeskVaultAPI.IVaultServices" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/AutodeskVaultAPI/" />
</baseAddresses>
</host>
</service>
<service name="SwaggerWcf.SwaggerWcfEndpoint">
<endpoint address="http://localhost:8733/docs" binding="webHttpBinding" contract="SwaggerWcf.ISwaggerWcfEndpoint" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="True" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="jsonEP">
<webHttp helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
Here is my service implementation:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[SwaggerWcf("/AutodeskVaultAPI/js")]
public class VaultWorker : IVaultServices
{
...[redacted]...
[SwaggerWcfTag("AutodeskVaultAPI")]
public AutodeskVaultFolder GetRootFolder(string vaultServerName = "", string currentUserLogin = "false")
{
try
{
Folder rootFolder = VaultConnection.WebServiceManager.DocumentService.GetFolderRoot();
if (null == rootFolder)
return null;
else
{
var toReturn = new AutodeskVaultFolder()
{
Created = rootFolder.CreateDate,
Category = (null == rootFolder.Cat) ? "No Category" : rootFolder.Cat.CatName,
CreatedByUserID = rootFolder.CreateUserId,
CreatedByUserName = rootFolder.CreateUserName,
EntityMasterID = rootFolder.Id,
FolderEntityName = rootFolder.Name,
FolderFullPath = rootFolder.FullName,
IsVaultRoot = true,
NumberOfChildren = rootFolder.NumClds,
ParentID = rootFolder.ParId
};
return toReturn;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
return null;
}
}
[SwaggerWcfTag("AutodeskVaultAPI")]
public AutodeskVaultSearchResponse SearchVault(AutodeskVaultSearchRequest request)
{
try
{
string bookMark = string.Empty;
var parameters = getSearchParametersFromRequest(request);
SrchStatus srchStatus = null;
List<File> foundFiles = new List<File>();
if (null != parameters && parameters.Length > 0)
{
while (null == srchStatus || foundFiles.Count < srchStatus.TotalHits)
{
File[] srcResults = VaultConnection.WebServiceManager.DocumentService.FindFilesBySearchConditions(parameters, null, null, true, false, ref bookMark, out srchStatus);
if (null != srcResults)
foundFiles.AddRange(srcResults);
else
break;
}
}
return mapResultsToResponse(request, foundFiles);
}
catch (Exception ex)
{
Debug.Write(ex);
return null;
}
}
...[redacted]...
[DataContract(Name = "AutodeskVaultSearchRequest")]
public class AutodeskVaultSearchRequest
{
[DataMember]
public bool OR_Search = false;
[DataMember]
public List<AutodeskVaultProperty> properties;
}
[DataContract(Name = "AutodeskVaultSearchResponse")]
public class AutodeskVaultSearchResponse
{
[DataMember]
public AutodeskVaultSearchRequest Request;
[DataMember]
public List<AutodeskVaultFile> Files;
[DataMember]
public string Message;
and here is my service interface:
[ServiceContract]
public interface IVaultServices
{
[SwaggerWcfPath("GetRootFolder", #"Test the default configured server to see if we can get back the root folder")]
[OperationContract]
[WebInvoke(UriTemplate = "GetRootfolder/{vaultServerName}/{currentUserLogin}", Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[Description(#"Test the default configured server to see if we can get back the root folder")]
AutodeskVaultFolder GetRootFolder(string vaultServerName = "", string currentUserLogin = "false");
[SwaggerWcfPath("GetAsbuiltDrawingsByNumber", #"Given an Autodesk Search Request, search through Vault to find File information using the supplied properties.")]
[OperationContract]
[WebInvoke(UriTemplate = "SearchVault", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[Description(#"Given an Autodesk Search Request, search through Vault to find File information using the supplied properties.")]
AutodeskVaultSearchResponse SearchVault(AutodeskVaultSearchRequest request);
}
Add an endpoint to your App.config file.
<services>
<service name="SwaggerWcf.SwaggerWcfEndpoint">
<endpoint address="http://localhost/docs" binding="webHttpBinding" contract="SwaggerWcf.ISwaggerWcfEndpoint" />
</service>
</services>
Create a WebServiceHost
var swaggerHost = new WebServiceHost(typeof(SwaggerWcfEndpoint));
swaggerHost.Open();
You can refer to the steps provided in the link for details.
https://github.com/abelsilva/swaggerwcf
How do I view my Swagger docs when using SwaggerWcf?
I am trying to set up a simple service that will allow the user to pass in a Pickup object as XML in the body of a POST. If i set the service to receive a Stream type, i can get it to work fine, but I'm not sure what i need to change in order for it to instead of a custom type is works fine. When I tell the server to expect a Pickup type i get "Request Error. The server has encountered..."
I someone could tell me what i need to change in the server/client to get this to work i would appreciate it very much.
My data Contract
[DataContract]
public class Pickup
{
[DataMember]
public string DelZip
{ get; set; }
}
Operation Contract
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "/pickups",
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare)]
string RequestPickup(Pickup pickup);
public string RequestPickup(Pickup pu)
{
return pu.DelZip;
}
config
<services>
<service name="TestAPI.Services.TestServices" >
<endpoint address=""
binding="webHttpBinding" behaviorConfiguration="webHttp"
contract="TestAPI.Services.ITestServices" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
my client code
const string url = "http://localhost:18463/TestServices.svc/pickups";
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/xml";
var xmlDoc = new XmlDocument { XmlResolver = null };
xmlDoc.LoadXml(#"<Pickup><DelZip>55555</DelZip></Pickup>");
string sXml = xmlDoc.InnerXml;
req.ContentLength = sXml.Length;
var sw = new StreamWriter(req.GetRequestStream());
sw.Write(sXml);
sw.Close();
res = (HttpWebResponse)req.GetResponse();
Stream responseStream = res.GetResponseStream();
var streamReader = new StreamReader(responseStream);
Thou there a dozen posts that cover how to call WCF methods from jQuery, I can't make it work. I have simple WCF service application
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string GetData(int value);
}
This is the implementation
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}
And this is the web.config of my service
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="TestWebApp.Service1AspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="TestWebApp.Service1AspNetAjaxBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="jQueryToWCF.Service1">
<endpoint address=""
behaviorConfiguration="TestWebApp.Service1AspNetAjaxBehavior"
binding="webHttpBinding"
contract="jQueryToWCF.IService1" />
</service>
</services>
Now I'm trying to call this from jQuery ( from html page )
$(document).ready(function () {
var param = "{value: 'Hello World!'}";
$.ajax({
type: "GET",
url: "http://localhost:5555/Service1.svc/GetData",
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
}
});
});
But no call even makes to Service. I checked it up by Fiddler. But when I'm puting the url into browser, I can get the response. Can anybody help me to figure this out ?
I've been struggling off and on with this for awhile.
The page that finally got me moving was this one: http://forums.asp.net/t/1765610.aspx/1
Meanwhile: Here is a functional project file that should work. You may need to replace the url in the javascript to be the correct port #.
http://submissiv.com/share/playground.wcf.service.zip
I am trying to get my application working by using REST, WCF and JSON (new to all those technologies). I have the 'GET' working fine. It is the 'POST' that is causing me problems.
As you will see below I 'pack up' my JSON using JSON.stringify, then fire off the POST to the REST resource. However, when the object gets to the WCF method that is handling the request the object is always null.
Here is the code:
$.ajax({
type: "POST",
dataType: "json",
url: "Services/ContactCompanyService.svc/contactcompanies/customers",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ contactcompany: newCustomer }),
success: function (html) { alert(html); }
});
Here is the config stuff:
<services>
<service behaviorConfiguration="ServiceBehaviour" name="ContactCompanyService">
<endpoint address="contactcompanies" behaviorConfiguration="web" binding="webHttpBinding" contract="IContactCompanyService"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
<enableWebScript/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"/>
Here is the contract:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "customers")]
[return: MessageParameter(Name = "ContactCompany")]
ContactCompany AddContactCompany(ContactCompany ContactCompanyObject);
And it is the method that implements the above interface where ContactCompanyObject is null.
What on earth am I doing wrong? Please don't rule out stupidity on my part.
Further:
I changed the WebMessageBodyStyle to .Bare, and this resulted in the object not being null ... but EVERY property of the object being null. That said, wrapped is the way I would like to go.
I would be grateful of any assistance. Let me know if you need further information.
UPDATE
I started from scratch with a completely new project - stripped back.
I am getting exactly the same result - the object, when received by the WCF code, is null.
Here's what I did on this new test project.
WCF Contract:
(under the namespace: NullTestService
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "NullTestPost")]
[return: MessageParameter(Name = "NullTestType")]
NullTestType GettMethod();
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "NullTestPost")]
[return: MessageParameter(Name = "NullTestType")]
NullTestType PostMethod(NullTestType NullTestTypeObject);
}
[DataContract]
public class NullTestType
{
[DataMember]
public string NullTestString { get; set; }
[DataMember]
public int NullTestInt { get; set; }
}
Service Implementation:
(same namespace)
public class Service1 : IService1
{
public NullTestType PostMethod(NullTestType NullTestTypeObject)
{
return NullTestTypeObject;
}
public NullTestType GettMethod()
{
return new NullTestType { NullTestString = "Returned String", NullTestInt = 25 };
}
}
Website project.
Service.svc:
<%# ServiceHost Service="NullTestService.Service1" %>
web.config in the web project:
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehaviour" name="NullTestService.Service1">
<endpoint address="nulltestaddress" behaviorConfiguration="web" binding="webHttpBinding" contract="NullTestService.IService1"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
and finally the jQuery in the web project:
$(function () {
// $.ajax({
// type: "GET",
// url: "http://localhost:8080/TestWeb/Service.svc/nulltestaddress/nulltestpost",
// success: alertResult
// });
alert('about to do it');
$.ajax({
type: "POST",
url: "http://localhost:8080/TestWeb/Service.svc/nulltestaddress/nulltestpost",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: '{"NullTestType":{"NullTestString":"This is a post string","NullTestInt":25}}',
success: alertResult
});
});
function alertResult(data) {
alert(data.NullTestType.NullTestString);
}
So. The (commented out) GET works fine and returns the JSON. The POST does not. On the line:
public NullTestType PostMethod(NullTestType NullTestTypeObject)
{
return NullTestTypeObject;
}
(the 'return' line) the NullTestTypeObject is always NULL.
I would be very grateful for help. I have lost a lot of time over this.
If Wrapped is what you want to do, then you need to wrap the request in the operation parameter name:
var input = { "ContactCompanyObject" : newCustomer };
$.ajax({
data: input
...
});
Or for the second example, if you change the ajax call to the one shown below, you should get the expected result:
var input = { NullTestTypeObject: { NullTestString: "Hello", NullTestInt: 123} };
alert("Input: " + JSON.stringify(input));
$.ajax({
type: "POST",
url: "./Service1.svc/nulltestaddress/NullTestPost",
contentType: "application/json",
data: JSON.stringify(input),
success: function (result) {
alert("POST result: " + JSON.stringify(result));
}
});
I have a WebHttpBinding WCF service that I am calling. My first POST method send the object correctly, but subsequent calls to POST methods are passing null for the object.
Here is my service:
public void Update(ObjectDTO objectDTO)
{
string token = WebOperationContext.Current != null ? WebOperationContext.Current.IncomingRequest.Headers["token"] : string.Empty;
//Authentication
bool isUserAuthenticatedResult = IsUserAuthenticated(ref token);
if (!isUserAuthenticatedResult)
return null;
//Perform service action
MyDtoManager = new MyDtoManager();
objectDTO = MyDtoManager.Update(objectDTO);
return objectDTO;
}
Here is my Service Contract:
[ServiceContract]
public interface IMyDtoService
{
[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
List<ObjectDTO> LoadById(string value);
[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
List<ObjectDTO> Load(string field, string value);
[OperationContract]
[WebInvoke(Method="GET", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
List<ObjectDTO> LoadAll();
[OperationContract(Name = "InsertSingle")]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
ObjectDTO Insert(ObjectDTO objectDto);
[OperationContract(Name = "UpdateSingle")]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
ObjectDTO Update(ObjectDTO objectDto);
[OperationContract(Name = "DeleteSingle")]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
ObjectDTO Delete(ObjectDTO objectDto);
}
Here is my server configuration:
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="WebHttpBindingConfig"
openTimeout="00:05:00"
sendTimeout="00:05:00"
maxBufferSize="65536000"
maxBufferPoolSize="52428800"
maxReceivedMessageSize="65536000"
transferMode="Buffered">
<readerQuotas maxDepth="32"
maxStringContentLength="65536000"
maxArrayLength="16384"
maxBytesPerRead="4096"
maxNameTableCharCount="16384" />
<security>
<transport />
</security>
</binding>
</webHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="Services.ServiceBehavior"
name="Services.MyDtoService">
<endpoint address=""
behaviorConfiguration="HttpBehavior"
binding="webHttpBinding"
name="Services.MyDtoService"
contract="ServiceInterfaces.IMyDtoService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Services.ServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="HttpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
And finally my client code making the call:
IMyDtoService myDtoService = new WebChannelFactory<IMyDtoService>(BindingConfig, new Uri("http://localhost:8080/MyDtoService.svc")).CreateChannel();
using (new OperationContextScope((IClientChannel)myDtoService))
{
if (WebOperationContext.Current != null)
WebOperationContext.Current.OutgoingRequest.Headers.Add("token", tokenResult.Result);
ObjectDTO insertResult = ipAddressService.Insert(new ObjectDTO
{ ObjectGuid = Guid.NewGuid(),
IsAllow = true,
Identifier = 1,
IdentifierType = 0,
StartIpAddress = "192.168.0.1"
});
List<ObjectDTO> loadByIdResult1 = myDtoService.LoadById(insertResult.ObjectGuid.ToString());
Console.WriteLine("Insert Found: " + loadByIdResult1.Count);
insertResult.IsAllow = false;
ObjectDTO updateResult = ipAddressService.Update(insertResult);
}
As you can see my client code calls my WCF service and the insert method works perfectly fine and I can see the persisted object in my database. However on the update, the ObjectDTO parameter is null. If I load an existing object and perform an update it works perfectly. It appears to be an issue with subsequent calls to the WCF service using POST methods. I do not have this problem with GET methods.
I have gone through this problem but WCF SOAP. On client site you can see object filled with values when debug point comes in service it is null. It had happened due to change in casing of param. . If you see your service contract has
ObjectDTO Update(ObjectDTO objectDto);
and defination has public void Update(ObjectDTO objectDTO) , note the difference in casing.
You have not shown the relevant code to be 100% sure what the problem is. But it looks like it is null because this line:
ObjectDTO insertResult = ipAddressService.Insert(new ObjectDTO
{ ObjectGuid = Guid.NewGuid(),
IsAllow = true,
Identifier = 1,
IdentifierType = 0,
StartIpAddress = "192.168.0.1"
});
is returning null. So you need to check the insert method.