Allright, I'm using a WCF service to handle requests from my web app and respond with a JSONP format. I tried all the solutions I could find, studied the documentation (http://msdn.microsoft.com/en-us/library/ee834511.aspx#Y200) and the example project.
The problem is the response object (json) does not get wrapped with the callback supplied in the URL.
Request is like:
http://localhost/socialApi/socialApi.svc/api/login?callback=callback&username=AAAAA&password=BBBB
Web.config looks like:
<?xml version="1.0"?>
<configuration>
<system.web>
<trace enabled="true"/>
<compilation debug="true" targetFramework="4.0"><assemblies><add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=*************" /></assemblies></compilation>
</system.web>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service name="RestService.socialApi">
<endpoint address="" binding="webHttpBinding" contract="RestService.IsocialApi" bindingConfiguration="webHttpBindingJsonP" behaviorConfiguration="webHttpBehavior">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="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" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior" >
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingJsonP" crossDomainScriptAccessEnabled="true"/>
</webHttpBinding>
</bindings>
<!--<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />-->
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<connectionStrings>
<add name="AsrAppEntities" connectionString="myconstring**********" />
</connectionStrings>
</configuration>
And my operationcontract:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.IO;
namespace socialApi
{
[ServiceContract]
public interface IsocialApi
{
[OperationContract]
[WebGet(
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/api/login?username={username}&password={password}")]
JsonpAuthenticationResponse Login(string username, string password);
}
}
The response is just normal json:
{"Message":"unauthorized","Status":400,"Token":null}
And I want:
callbackfunction({"Message":"unauthorized","Status":400,"Token":null})
I think it has something to do with the Web.config, because when I modify the example and adjust the Web.config so it looks like mine the example doesn't function anymore. You would say I pinpointed the problem.. but no.
To supply as much as information as possible, here is the working solution from the example:
Web.config:
<?xml version="1.0"?>
<!-- Copyright (c) Microsoft Corporation. All rights reserved. -->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="None" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint name="" crossDomainScriptAccessEnabled="true"/>
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>
And the class:
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
namespace Microsoft.Samples.Jsonp
{
[DataContract]
public class Customer
{
[DataMember]
public string Name;
[DataMember]
public string Address;
}
[ServiceContract(Namespace="JsonpAjaxService")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CustomerService
{
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public Customer GetCustomer()
{
return new Customer() { Name="Bob", Address="1 Example Way"};
}
}
}
The above example returns a jsonp object. This is the call from the example:
function makeCall() {
var proxy = new JsonpAjaxService.CustomerService();
proxy.set_enableJsonp(true);
proxy.GetCustomer(onSuccess, onFail, null);
}
proxy.set_enableJsonp(true); is maybe something I am missing in my call? But I can't add this in my call because I'm not calling the service from the same solution.
So any idea's about what's causing the normal JSON response instead of the request JSONP?
The problem was in the factory settings. In the marckup of the svc file I had to change the factory to System.ServiceModel.Activation.WebScriptServiceHostFactory.
Related
I need to know if I can create a WCF service using TFTP to get data from a device. I know I can create an application using C# to do this but I am trying to make it a web based application. Also the WCF needs to be hosted on IIS. I want to use a WCF service to start a connection and then pull an image from my device. When I run my code it does not seem to have a problem with the SendTo command but it always gives me a "System.Net.Sockets.SocketException (0x80004005): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond at System.Net.Sockets.Socket.ReceiveFrom(...). Is this because I am using a netTcpBinding? Can I do this using a basic HTTP binding or something else? Or maybe it just isn't possible to create this service using WCF, thoughts??
Service Code Snippet:
public byte[] ipTftpGet(String xferFileName)
{...
byte[] rcvBuffer = new byte[5200];
....
try
{
ipEndPointFtp = new IPEndPoint(ipAddress, 69);
tftpS = new Socket(ipEndPointFtp.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
remoteEP = ipEndPointFtp;
// Request and Receive first Data Packet From TFTP Server
tftpS.SendTo(sndBuffer, nameLen, System.Net.Sockets.SocketFlags.None, remoteEP);
tftpS.ReceiveTimeout = 1000;
try
{
len = tftpS.ReceiveFrom(rcvBuffer, ref remoteEP);//tftpS.ReceiveFrom(rcvBuffer, ref remoteEP);
rcvBuffer[len] = 0x00;
}
catch (System.Net.Sockets.SocketException ex)
{
xferValid = false;
errMsgStr = ex.ToString();
}
}
Web.config:
<services>
<service behaviorConfiguration="mexBehavior"
name="ComService.ComService">
<endpoint address="ComService" binding="netTcpBinding"
contract="ComService.IComService" />
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:8090" />
<add baseAddress="http://localhost:8080" />
</baseAddresses>
</host>
</service>
</services>
I was able to determine the problem. TFTP uses UDP and apparently you cannot use IIS to host the service. You can host the service using a Windows Console or Windows Forms application. I created a simple console application and then updated my web.config (now an App.config) as follows:
Program.cs:
namespace TFTPConsoleHost
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(TFTPService.TFTPService)))
{
host.Open();
Console.WriteLine("Host started # " + DateTime.Now.ToString());
Console.ReadLine();
}
}
}
}
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
</startup>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceThrottling maxConcurrentCalls="1000" maxConcurrentInstances="1000" maxConcurrentSessions="1000"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<netTcpBinding>
<binding name="unsecured">
<security mode="None"/>
</binding>
</netTcpBinding>
</bindings>
<services>
<service name="TFTPService.TFTPService">
<endpoint address="soap.udp://localhost:8060/" binding="udpBinding" contract="TFTPService.ITFTPService"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8060/"/>
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
i am having this issue and i looked in all the web and saw lots of answers but nothing helped me
my issue is that i every time i make get from the wcf service its 400 bad request
but when i run the wcf test client it works fine
i am using vs 2015
my config file (which vs generated automatically )
<?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=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<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="BasicHttpBinding_IProductService" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8733/Design_Time_Addresses/Test/Service1/"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IProductService"
contract="ServiceReference.IProductService" name="BasicHttpBinding_IProductService" />
</client>
<services>
<service name="Test.ProductService">
<endpoint address="" binding="basicHttpBinding" contract="Test.IProductService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/Design_Time_Addresses/Test/Service1/" />
</baseAddresses>
</host>
</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>
</behaviors>
</system.serviceModel>
<connectionStrings>
<add name="modelEntities" connectionString="metadata=res://*/Products.csdl|res://*/Products.ssdl|res://*/Products.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=test;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
and the service is
public interface IProductService
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json,UriTemplate = "/GetProducts")]
List<Product> GetProducts();
}
and this is the impplement method
public List<Product> GetProducts()
{
modelEntities context = new modelEntities();
var productEntity = (from p in context.productEntities select p);
List<Product> products = new List<Product>();
foreach (var item in productEntity)
{
products.Add(TranslateProductEntityToProduct(item));
}
return products;
}
i was trying without the webinvoke
also tried webget
and also try to replace the basichttpbinding with webbinding
and also look for many answers here and on the net and nothing helped me
hope you an help me
Thanks
I'm trying to use basic authentication with my WCF Rest/JSON service.
Therefore I've create a class which derives from "UserNamePasswordValidator" and added it to my web.config.
In IIS only Basic Authentication is enabled.
Unfortunately this class is never called. When I call a rest method in my browser the dialog for entering the username and password is shown but nothing happens after that.
Here my web.config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext"
value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<identity impersonate="true" />
</system.web>
<system.serviceModel>
<services>
<service name="myTimeMvc.Webservice.MyTimeRestService"
behaviorConfiguration="returnFaults">
<endpoint behaviorConfiguration="restfulBehavior"
binding="webHttpBinding"
bindingConfiguration="webBinding"
contract="myTimeMvc.Webservice.IMyTimeRestService" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="webBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic" />
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="restfulBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="returnFaults">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<serviceCredentials>
<!--<serviceCertificate findValue="MyWebSite"
storeLocation="LocalMachine"
storeName="My"
x509FindType="FindBySubjectName" />-->
<userNameAuthentication userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="myTimeServiceDemoa.WcfExtension.CustomUserNameValidator,TestWcfServiceAuth" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</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" />
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
</configuration>
Here my CustomUserNameValidator.cs
namespace myTimeServiceDemoa.WcfExtension
{
public class CustomUserNameValidator : System.IdentityModel.Selectors.UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (null == userName || null == password)
{
throw new ArgumentNullException("You must provide both the username and password to access this service");
}
if (!(userName == "user1" && password == "test") && !(userName == "user2" && password == "test"))
{
throw new FaultException("Unknown Username or Incorrect Password");
}
}
}
}
UPDATE:
After two days of trying I give up now because I don't see what I may have done wrong. Seems this stuff is not working for me...
I investigated a lot and everything you need is to change Authentication of your WebApplication in IIS to "Basic" and add a custom "CustomUserNameValidator" in your web.config but this is not working!
Please correct me if I'm wrong.
My solution:
Use "Anonymous Authentication" in IIS
Use a "ServiceAuthorizationManager" and check HTTP-Headers in "CheckAccessCore"
Cheers,
Stefan
I was trying to make a webservice call to return json formatted data to populated a grid control. It was not working and after using fiddler and firebug to monitor the call I see the data wrapped as xml. I tried to different calls; one makes a call to mongodb and the result is a simply collection and the other is data from another endpoint that is json format. I have the webservice set up as follows:
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Web.Script.Services
Imports System.Web.Script.Serialization
Imports System.Net
Imports System.IO
Imports System.Xml
Imports Newtonsoft.Json
Imports System.ServiceModel
Imports MongoDB.Driver
Imports MongoDB.Bson
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ServiceBehaviorAttribute(IncludeExceptionDetailInFaults:=True)>
<ToolboxItem(False)> _
Public Class WebService1
Inherits System.Web.Services.WebService
Private mongo As MongoServer = MongoServer.Create()
Private Function convertToJson(ByVal username As String)
Dim product As New splnkObject()
product.userName = username
Dim jsonT As String = JsonConvert.SerializeObject(product)
Return jsonT
End Function
<WebMethod()> _
<ScriptMethod(UseHttpGet:=True,
XmlSerializeString:=False, ResponseFormat:=ResponseFormat.Json)> _
Public Function getDBData() As String
Dim response As String = String.Empty
mongo.Connect()
Dim db = mongo.GetDatabase("nodetest1")
Using mongo.RequestStart(db)
Dim collection = db.GetCollection(Of BsonDocument)("usercollection").FindAll()
response = collection.Collection.ToString
response = "{""d"":" + response + "}"
Return collection.ToArray.ToJson
End Using
End Function
This is the response captured in fiddler and the json tab says invalid json in body:
string [ xmlns=http://tempuri.org/ ]
[{ "_id" : ObjectId("52d2f2b3c60804b25bc5d2ca"), "username" : "testuser1",
"email" : "testuser1#testdomain.com" },
{ "_id" : ObjectId("52d2f2f9c60804b25bc5d2cb"), "username" : "testuser2",
"email" : "testuser2#testdomain.com" },
{ "_id" : ObjectId("52d2f2f9c60804b25bc5d2cc"), "username" : "testuser3",
"email" : "testuser3#testdomain.com" }]
My webconfig file as follows:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="connectionString2" value="Server=localhost:27017"/>
</appSettings>
<connectionStrings>
<system.web>
<authentication mode="None" />
<authorization>
<allow users="?" />
</authorization>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Linq, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx"
type="System.Web.Script.Services.ScriptHandlerFactory" validate="false"/>
</httpHandlers>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false"
multipleSiteBindingsEnabled="true" />
<services>
<service name="WbTest.Service1">
<endpoint address="" behaviorConfiguration="WbTest.Service1AspNetAjaxBehavior"
binding="webHttpBinding" contract="WbTest.IService1" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp />
<enableWebScript />
</behavior>
<behavior name="WbTest.Service1AspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings />
<client />
</system.serviceModel>
</configuration>
The javascript call:
var myStore = new Ext.data.Store({
model: 'User',
proxy: {
type: 'ajax',
url: 'WCFService/WebService1.asmx/getDBData',
contentType: 'application/json; charset=utf-8',
reader: {
type: 'json',
root: '_id'
}
}
});
myStore.load();
Please could someone take a look and identify where the issue is.
I'm not going to say this is the "right" way, however, one option would be to not specify a return type on the method and write directly to the response(HttpContext.Current.Response) object.
<WebMethod()> _
Public Sub getDBData()
Dim response As String = String.Empty
mongo.Connect()
Dim db = mongo.GetDatabase("nodetest1")
Using mongo.RequestStart(db)
Dim collection = db.GetCollection(Of BsonDocument)("usercollection").FindAll()
response = collection.Collection.ToString
response = "{""d"":" + response + "}"
Dim responseJson as String
responseJson = Collection.ToArray.ToJson
HttpContext.Current.Response.Write(responseJson)
End Using
End Sub
Additionally, If you are going to use Newtonsoft to manipulate objects, i find this method works well.
I should note, that asmx web services are legacy and the newer technology is wcf.
I created a simple WCF Service interface:
namespace ApiDoc.SampleApi
{
/// <summary>
/// Contract
/// </summary>
/// <webMethodsPrefix>Web</webMethodsPrefix>
[ServiceContract(Namespace = "apidoc.sampleapi.com", Name = "SampleApi")]
public interface IService
{
[WebGet( UriTemplate = "Add?value1={value1}&value2={value2}&apiKey={apiKey}", BodyStyle = WebMessageBodyStyle.Bare)]
AddRs AddWithHttpGet(int value1, int value2, string apiKey);
[WebInvoke(Method = "POST", UriTemplate = "Add", BodyStyle = WebMessageBodyStyle.Bare)]
AddRs Add(AddRq rq);
}
}
In this case it is just a simple Add operation.
It works well for Xml, Soap and Json. Both Get and Post.
The issue I am having is in Soap when I create a Service Reference to this service. I can call both functions "Add" and "AddWithHttpGet", while I only would like to see "Add".
I originally thought it was related to using "OperationContract" attribute, but it seems like it is not used any longer. I tried adding this attribute only to POST Add, but it doesn't make any difference. I am using ASP.NET 4.0.
Another solution would be to create a different IService for Soap, but I would rather keep this all in one interface.
Here is my config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="jsonHttpBinding" />
<binding name="xmlHttpBinding" />
</webHttpBinding>
</bindings>
<services>
<service name="ApiDoc.SampleApi.Service" behaviorConfiguration="ApiDocSampleApiBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost/ApiDoc.SampleApi/" />
</baseAddresses>
</host>
<endpoint name="soap" address="" binding="basicHttpBinding" bindingNamespace="apidoc.sampleapi.com" contract="ApiDoc.SampleApi.IService" lockAttributes="bindingNamespace" />
<endpoint name="json" address="json" binding="webHttpBinding" bindingNamespace="apidoc.sampleapi.com" bindingConfiguration="jsonHttpBinding" contract="ApiDoc.SampleApi.IService" behaviorConfiguration="JsonBehavior" />
<endpoint name="xml" address="xml" binding="webHttpBinding" bindingNamespace="apidoc.sampleapi.com" bindingConfiguration="xmlHttpBinding" contract="ApiDoc.SampleApi.IService" behaviorConfiguration="XmlBehavior" />
<endpoint name="mex" address="mex" binding="mexHttpBinding" bindingNamespace="apidoc.sampleapi.com" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="JsonBehavior">
<webHttp defaultOutgoingResponseFormat="Json" />
</behavior>
<behavior name="XmlBehavior">
<webHttp defaultOutgoingResponseFormat="Xml" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ApiDocSampleApiBehavior">
<serviceMetadata httpGetEnabled="true" httpGetUrl="" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" minFreeMemoryPercentageToActivateService="0" />
</system.serviceModel>
...
I would create a separate interface.
Think of your interface like a real contract between two parties. You are using it to define what operations are available to a client. If it's in the contract, it's available.
Instead of looking for some sort "invisible ink" that would make certain parts of the contract available to certain clients, I'd simply create two contracts.
I'm a little confussed. The OperationContractAttribute is required. A WebGetAttribute on it's own shouldn't do anything, as the method is not expossed as an operation.
As for hiding an operation, that is not possable either. If the interface is your contract, and you definatly want two different contracts then you will need two different interfaces.
If you don't want to duplicate your code then you can still use inheritace. Have one interace define your SOAP operation Add and then inherit from that to add AddWithHttpGet. Then by targeting the different interfaces in your endpoints, the SOAP endpoint would have one operation and REST endpoint would have two.
try this you want hide webmethod form soap header in c#
[SoapDocumentMethod(ParameterStyle = SoapParameterStyle.Bare), WebMethod]
public string Operation(RIL_OB_MSG RIL_OB_MSG)
{
}