I want my WCF service to return json.
I'm using Visual Studio 2013 (VB.NET/ASP.NET 4.6.1)
In My aspx page (located on a folder called DataUnit) i try to call my WCF service located (at the moment) on the same folder of aspx page.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'Service.svc/GetCustomers',
data: '{"MyDate": "' + dateval + '"}',......
But i receive Error 404
If i visualize Service.svc in Browser (http://localhost:64367/DataUnit/Service.svc) i receive message
Service Created
To Test Service.....
svcutil.exe http://localhost:64367/DataUnit/Service.svc?wsdl
I've also activated in Panel Control
Windows Communication Foundation HTTP Activation
Windows Communication Foundation Non-HTTP Activation
I've passed all day to resolve but i'm getting crazy.
This is my code
web.config
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="ServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service name="MyNameSpace.Service" behaviorConfiguration="ServiceBehavior">
<endpoint address="" binding="webHttpBinding" contract="MyNameSpace.Service" behaviorConfiguration="ServiceAspNetAjaxBehavior">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
</services>
</system.serviceModel>
Service.svc
Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.ServiceModel.Web
Imports Newtonsoft.Json
<ServiceContract()>
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)>
Public Class Service
<OperationContract()>
<System.ServiceModel.Web.WebInvoke(Method:="POST", _
ResponseFormat:=System.ServiceModel.Web.WebMessageFormat.Json)> _
Public Function GetCustomers(ByVal MyDate As String) As String
Try
Dim gd As New GetOracleData
Dim b As String = Chr(34)
Dim newdataset As DataSet
Dim RAPPID As String = "01"
newdataset = gd.GetMyData(MyDate , RAPPID)
Dim json2 As String = JsonConvert.SerializeObject(newdataset, Newtonsoft.Json.Formatting.Indented)
Return json2
Catch ex As Exception
End Try
End Function
End Class
SVC Markup:
<%# ServiceHost Language="VB" Debug="true" Service="MyNameSpace.Service" CodeBehind="Service.svc.vb" %>
RouteConfig.vb
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.Mvc
Imports System.Web.Routing
Public Module RouteConfig
Public Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
routes.MapRoute(
name := "Default",
url := "{controller}/{action}/{id}",
defaults := New With {.action = "Index", .id = UrlParameter.Optional}
)
End Sub
End Module
UPDATE
I believe that problem is on this but i don't know why and how i must implement a controller for a simple ASPX page.
[HttpException]: The controller for path '/DataUnit/Service.svc/GetCustomers' was not found or does not implement IController.
in System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
in System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
in System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
in System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
in System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
in System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
in System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
in System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
in System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
Bro,
We need to add the WebHttp endpoint behavior to the service endpoint. Like below.
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WebApplication1.CostServiceAspNetAjaxBehavior">
<enableWebScript/>
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
<services>
<service name="WebApplication1.CostService">
<endpoint address="" behaviorConfiguration="WebApplication1.CostServiceAspNetAjaxBehavior" binding="webHttpBinding" contract="WebApplication1.CostService"/>
</service>
</services>
</system.serviceModel>
For details.
https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/wcf/webhttp
Feel free to let me know if the problem still exists.
Related
I have just added a new webservice, but when I approach it, I get: Endpoint not found.
on URL http://www.testsite.com/service.svc/getcompanyreviewdetails/?id=315&t=1
I have another service where the endpoint IS found:
http://www.testsite.com/service.svc/getshopitems/?newurl=myurl
When I request http://www.testsite.com/service.svc?wsdl, I also don't see the getcompanyreviewdetails method in that list.
Here's my code:
Iservice.vb
Namespace RestService
<ServiceContract()>
Public Interface Icompanyservice
<OperationContract()> _
<Web.WebInvoke(Method:="GET", ResponseFormat:=Web.WebMessageFormat.Json, BodyStyle:=Web.WebMessageBodyStyle.Bare, _
UriTemplate:="getcompanyreviewdetails/?id={id}&t={t}")> _
Function getCompanyReviewDetails(ByVal id As Integer, ByVal t As Integer) As Stream
End Interface
<ServiceContract()>
Public Interface Iservice
<OperationContract()> _
<Web.WebInvoke(Method:="GET", ResponseFormat:=Web.WebMessageFormat.Json, BodyStyle:=Web.WebMessageBodyStyle.Bare, _
UriTemplate:="getshopitems/?newurl={newurl}")> _
Function getShopItems(ByVal newURL As String) As Stream
End Interface
End Namespace
service.svc.vb
Namespace RestService
<ServiceContract(Namespace:="RestService")>
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class companyservice
Implements Icompanyservice
Public Function getCompanyReviewDetails(ByVal id As Integer, ByVal t As Integer) As Stream Implements Icompanyservice.getCompanyReviewDetails
End Function
End Class
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class service
Implements Iservice
Public Function getShopItems(ByVal newURL As String) As Stream Implements Iservice.getShopItems
End Function
End Class
End Namespace
when adding a service reference I don't see the companyservice
solution explorer
web.config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<client/>
<services>
<service name="RestService.service">
<endpoint behaviorConfiguration="webHttp" binding="webHttpBinding" contract="RestService.Iservice" />
</service>
<service name="RestService.companyservice">
<endpoint address="http://www.testsite.com/service.svc" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" contract="RestService.Icompanyservice" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp/>
</behavior>
<behavior name="webHttpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
UPDATE: configuring 2 endpoints
<client>
<endpoint name="basic" address="http://www.testsite.com/service.svc" binding="basicHttpBinding" contract="RestService.Iservice" />
</client>
<services>
<service name="RestService.service" behaviorConfiguration="webHttpBehavior"> <!-- in this case the property behaviorConfiguration is incorrect according to its datattype serviceBehaviorConfigurationType, I don't know what other value to provide here -->
<endpoint address="" binding="basicHttpBinding" contract="RestService.Iservice" />
</service>
</services>
I then tried:
<client />
<services>
<service name="RestService.service">
<endpoint behaviorConfiguration="webHttp" binding="webHttpBinding" contract="RestService.Iservice" />
<endpoint address="http://www.testsite.com/service.svc" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" contract="RestService.Icompanyservice" />
</service>
</services>
The contract name 'RestService.Icompanyservice' could not be found in the list of contracts implemented by the service 'service'.
So I tried moving all method of Icompanyservice under Iservice again and remove everything related to Icompanyservice. Also changed the web.config to:
<service name="RestService.service">
<endpoint behaviorConfiguration="webHttp" binding="webHttpBinding" contract="RestService.Iservice" />
<endpoint address="http://www.testsite.com/service.svc" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" contract="RestService.Iservice" />
</service>
I then got:
When 'system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled' is set to true in configuration, the endpoints are required to specify a relative address. If you are specifying a relative listen URI on the endpoint, then the address can be absolute. To fix this problem, specify a relative uri for endpoint 'http://www.testsite.com/service.svc'.
So I set it to:
<endpoint address="/service.svc" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" contract="RestService.Iservice" />
Then both services work, but how can I validate if service getcompanyreviewdetails is now JSONP instead of JSON?
Example.svc.vb no interface.
<ServiceContract(Namespace:="{namespace the service resides in}")>
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)>
Public Class ExampleService
Then adorn your methods in here as you would <OperationalContract>MethodName...
ServiceReference.ClientConfig - I have 2 endpoints one for testing local and the other for publish - remember to comment out one or the other depending on what your doing(publishing vs testing).
<endpoint address="http://{your domain}/ExampleService.svc"
binding="customBinding" bindingConfiguration="CustomBinding_ExampleService"
contract="ExampleServRef.ExampleService" name="CustomBinding_ExampleService" />
<endpoint address="http://{localhost:port}/ExampleService.svc"
binding="customBinding" bindingConfiguration="CustomBinding_ExampleService"
contract="ExampleServRef.ExampleService" name="CustomBinding_ExampleService" />
A Developer's Introduction to Windows Communication Foundation
WCF Multiple Endpoints
As it normally happens, I accidentally overwrote my web.config file this morning that has my WCF settings already working perfectly. As you would expect, no backup...shame shame shame on me.
That being said, I can't seem to get my configuration working again.
Here is the error that I keep getting back from IIS/ASP.NET
The message with Action '' cannot be processed at the receiver, due to
a ContractFilter mismatch at the EndpointDispatcher. This may be
because of either a contract mismatch (mismatched Actions between
sender and receiver) or a binding/security mismatch between the sender
and the receiver. Check that sender and receiver have the same
contract and the same binding (including security requirements, e.g.
Message, Transport, None).
Here is an overview of what I have setup.
My Web Config:
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="Binding1" maxReceivedMessageSize="10000000">
<readerQuotas maxArrayLength="10000000" />
<security mode="Transport"></security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
<services>
<service name="MyService">
<endpoint address="" binding="webHttpBinding" bindingConfiguration="Binding1" contract="IMyService" />
</service>
</services>
</system.serviceModel>
Here is the declaration in my Service Contract:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/SSMX", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
sqlStudio_Table_Permissions SSMX(string TableName);
Sadly I just can't seem to remember what I did in my previous configuration to make this work.
Any help would be appreciated.
I am trying to create a restful wcf web service. When I try to connect to the service through the client I get the following error:
The service cannot be activated because it does not support ASP.NET compatibility. ASP.NET compatibility is enabled for this application. Turn off ASP.NET compatibility mode in the web.config or add the AspNetCompatibilityRequirements attribute to the service type with RequirementsMode setting as 'Allowed' or 'Required'.
Others have had problems, but they fixed it through changes to their web.config. I have implemented their fix, but still the problem exists. here is my web.config:
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WebBehavior" >
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="MyServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="MyServiceBehavior" name="myfirstwcf">
<endpoint address="ws" binding="basicHttpBinding"
contract="Imyfirstwcf" />
<endpoint address="ws2" binding="wsHttpBinding"
contract="Imyfirstwcf" />
<endpoint address="" behaviorConfiguration="WebBehavior"
binding="webHttpBinding"
contract="Imyfirstwcf" />
<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled= "true"
multipleSiteBindingsEnabled="true" />
</system.serviceModel>
On your main service you could mark your service as:
[AspNetCompatibilityRequirements(
RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
From http://forums.silverlight.net/t/21944.aspx
it will work :
you have change this lines in code or add the line in web.config:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
If someone has a lot of services and services are created using custom ServiceHostFactory, then AspNetCompatibilityRequirementsAttribute can also be set in CreateServiceHost method.
Example:
public class HostFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
var host = new ServiceHost(serviceType, baseAddresses);
//other relevent code to configure host's end point etc
if (host.Description.Behaviors.Contains(typeof(AspNetCompatibilityRequirementsAttribute)))
{
var compatibilityRequirementsAttribute = host.Description.Behaviors[typeof(AspNetCompatibilityRequirementsAttribute)] as AspNetCompatibilityRequirementsAttribute;
compatibilityRequirementsAttribute.RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed;
}
else
{
host.Description.Behaviors.Add(new AspNetCompatibilityRequirementsAttribute() { RequirementsMode =AspNetCompatibilityRequirementsMode.Allowed});
}
return host;
}
}
Actually, as per the latest documentation you need to do 2 things,
1.For your service class:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(Namespace = "url")]
public class Service : IService
{
}
2.For web.config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
I need to use wsHttpBinding binding because my service needs access to HttpContext.Current.Session. I understand from my research that this is not possible with webHttpBinding. However all of my ajax is written to use JSON and I would like it very much if I didn't have to rewrite all of it.
My service works perfectly with webHttpBinding until I need to use the session.
Or, is there a way to get webHttpBinding access to the session?
EDIT:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<behaviors>
<endpointBehaviors>
<behavior name="LiteBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="LiteBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="LiteBehavior" name="Lite.CMS.Services.LiteService">
<endpoint behaviorConfiguration="LiteBehavior" address="" binding="webHttpBinding" contract="Lite.CMS.Services.Interfaces.ILiteService" />
</service>
</services>
</system.serviceModel>
And my contract:
[ServiceContract (SessionMode=SessionMode.Allowed)]
public interface ILiteService
{
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
[OperationContract]
void Item_Save(string Name);
}
And Implementation:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class LiteService : ILiteService
{
public void Item_Save(string Name)
{
// I can't get access to HttpContext.Current.Session variables here.
}
}
webHttpbinding is a stateless binding, it doesn't use SOAP.
If you try to put SessionMode=SessionMode.Required it will throw an error on service start.
If you want to implement session on a stateless protocol, you'll need to do it by hand with cookies.
See :
http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/fe2a2ce9-ba97-4784-95f8-bdce5ffcd8eb/
How to Manage Sessions in Restful WCF Service
REST WCF service and Session‏ in ASP.NET
I'm new to WCF world. i'm having a solution which contains Web App(which has JQuery Ajax call to WCF services application which is another project in the solution. After 2 days of working(cracking) i'm in a state which i able pass request and get response
but while try to show that in alert gives me 200 parser Error.
Any help will be highly appreciate
Further Ref
$.ajax({
async: true,
type: 'GET', //GET or POST or PUT or DELETE verb
url: 'http://localhost:61057/Service1.svc/GetCustomer', // Location of the service
dataType: 'jsonp', //Expected data format from server
success: function (data) {//On Successfull service call
ServiceSucceeded(data);
},
error: function () { ServiceFailed(Data); } // When Service call fails
});
Web.config
<system.serviceModel>
<services>
<service name="FIN.Services.Service1" behaviorConfiguration="DefaultBehavior">
<endpoint address="http://localhost:61057/service1.svc" binding="webHttpBinding" contract="FIN.Services.IService1" behaviorConfiguration="AjaxBehavior">
<identity>
<dns value="locahost"/>
</identity>
</endpoint>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="webBinding">
<security mode="None">
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="AjaxBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
service interface :
[WebInvoke(ResponseFormat = WebMessageFormat.Json, Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json)]
[OperationContract]
string GetCustomer();
If you need no argument, add following in your ajax call ..
data: "{}",
You are using jsonp,means you want to call cross domain service.
For cross domain service you url should be like below
http://localhost:61057/Service1.svc/GetCustomer?callback=?
and also you have to make some changes in web.config
Check out the following link for complete example
Calling cross domain service in wcf