Hi all I'm trying to build WCF rest (Ajax enabled) I watch some tutorial in the YouTube as well as I read some questions about this topic in Stackoverflow.
I found some missing element in my web.config I thought the problem was completely fixed, but unfortunately I'm facing new problem now that is service not found.
this is web.config
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="AjaxAndWCF.GetEmployeeAspNetAjaxBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="AjaxAndWCF.GetEmployee" behaviorConfiguration="ServiceBehavior">
<endpoint address="../GetEmployee.svc" behaviorConfiguration="AjaxAndWCF.GetEmployeeAspNetAjaxBehavior"
binding="webHttpBinding" contract="AjaxAndWCF.IGetEmployee" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:51520/GetEmployee.svc/"/>
</baseAddresses>
</host>
</service>
</services>
this is the service
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class GetEmployee : IGetEmployee
{
public Employee byId(int id)
{
Employee emp = new Employee();
String strcon = ConfigurationManager.ConnectionStrings["WCFTOAJAXT1ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strcon))
{
SqlCommand cmd = new SqlCommand("ProGetEmployeeById", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#Id";
parameter.Value = id;
cmd.Parameters.Add(parameter);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
emp.Id = Convert.ToInt32(rdr["Id"]);
emp.Name = rdr["Name"].ToString();
emp.Nationality = rdr["Nationality"].ToString();
emp.Email = rdr["Email"].ToString();
}
}
return emp;/*
return new Employee()
{
Id = 1,
Name = "test",
Nationality = "test",
Email ="test#test.com"
};*/
}
}
this is the service contract
[OperationContract]
[WebInvoke(UriTemplate = "/byId?id=id",
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json)]
Employee byId(int id);
The Address in the endpoint is BASED off of the base address. Since you don't seem to have any other endpoints, you may as well hang your RESTFUL webservice off of the root address...blank out the address in your endpoint like below and let me know if this fixes it.
<service name="AjaxAndWCF.GetEmployee"
behaviorConfiguration="ServiceBehavior">
<endpoint address=""
behaviorConfiguration="AjaxAndWCF.GetEmployeeAspNetAjaxBehavior"
binding="webHttpBinding"
contract="AjaxAndWCF.IGetEmployee" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:51520/GetEmployee.svc/"/>
</baseAddresses>
</host>
</service>
And then your url will be http://localhost:51520/GetEmployee.svc/byid?id=5
I usually format my urls like "/byid/{id}" so I haven't tried to see if this method works, but I'm assuming you got that code from somewhere.
Related
I have a WCF Service with a SOAP endpoint. I added a REST endpoint and the Get methods are working just fine. I am having trouble with a POST method which takes in an object and returns a different object. When I pass in my object, I get this error back:
"Message":"Object reference not set to an instance of an object."
Here's the code to call the service:
string URL = "http://qa.acct.webservice";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var request = new RequestGetInventory
{
BrandIDs = new string[] { "4", "42" },
AccountID = "9900003"
};
var resp = client.PostAsJsonAsync("/AxaptaService.svc/rest/GetInventory", request);
response = resp.Result;
if (response.IsSuccessStatusCode)
{
var temp = response.Content.ReadAsStringAsync().Result;
MessageBox.Show(temp); //error message received here.
}
The RequestGetInventory object is defined as follows:
[DataContract]
public class RequestGetInventory
{
[DataMember]
public string[] BrandIDs { get; set; }
[DataMember]
public string AccountID { get; set; }
}
The contract for the webservice is defined as follows:
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json)]
ResponseGetInventory GetInventory(RequestGetInventory Request);
I tried playing around with the WebInvoke parameters, but received the same error message for all viable attempts.
And this is how my web.config is set up:
<system.serviceModel>
<services>
<service behaviorConfiguration="" name="Proj.AxaptaUS.WebService.AxaptaService">
<endpoint address="rest" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="Proj.Interfaces.Axapta3.IAxaptaService"></endpoint>
<endpoint address="" binding="basicHttpBinding" contract="Proj.Interfaces.Axapta3.IAxaptaService"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp helpEnabled="true" />
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
I am not entirely sure what I'm doing wrong because I can access this using SOAP just fine. It seems like it is not getting any values for the object which I passed in, thus causing the object reference error.
Any help would be greatly appreciated! Thanks!
#jstreet posted a comment which ended up working.
I changed BodyStyle = WebMessageBodyStyle.WrappedRequest to BodyStyle = WebMessageBodyStyle.Bare and removed <enableWebScript/> from config file.
After doing those things, it started to work correctly! thanks #jstreet!
I am having trouble developing and testing a POST web service which both receives and returns JSON.
I am testing it (or trying/wanting to test it) by calling it from a form in a test project within the same
solution as the web service. However it seems that no matter what I do, I'm getting either a "Bad Request", or
a "Not Found" error when invoking the service.
There are oodles of posts on the web in relation to these things, and WCF in general, with examples etc, but I
cannot seem to solve the problem and it's quite disheartening :-((.
I am using VS 2010 on (don't laugh) win XP. However I don't see why an outdated OS should matter.
The single method's signature is
public Stream ReceiveCardStatusInfo(Stream request)
I have generated a proxy via svcutil, but I'm not using it. I have tried referencing the webservice project as
both an ordinary and a service reference (currently a service reference). The properties of the projects are
pretty much the defaults, but in trying to resolve the issues, the web page of the WS project currently shows
"Use Visual Studio Development Server" with "Specific Port" selected, port number 1318. (Virtual Path is the
default "/").
As I'm not really sure exactly what the problem is, I am providing all my code and config files;
the Form's logic first (used to invoke the service) and the app.config for that project, with the service
components following:
Form1:
public Form1() {
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e) {
var request = (HttpWebRequest)WebRequest.Create("http://localhost:1318/ReceiveData.svc/ReceiveCardStatusInfo"); // /ReceiveCardStatusInfo
request.ContentType = "text/json";
request.Method = "POST";
string json = new JavaScriptSerializer().Serialize(new {
AuthenticationToken = "...",
Campus = "Te Awamutu",
StudentID = "200122327",
EnrolmentEndDate = "11/06/2015",
CardStatus = "Suspended",
SuspendedDate = "18/08/2014",
OrderedDate = "20/09/2014",
ReprintDate = "07/10/2014"
});
using (var sW = new StreamWriter(request.GetRequestStream())) {
sW.Write(json);
sW.Flush();
sW.Close();
}
var response = (HttpWebResponse)request.GetResponse();
string result;
using (var streamReader = new StreamReader(response.GetResponseStream())) {
result = streamReader.ReadToEnd();
}
MessageBox.Show(result);
}
app.config (I don't really understand exactly what needs to be in this file, but I've had trouble finding a
clear answer to this, so it contains what it does):
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="StudentCardStatusData.ReceiveData" behaviorConfiguration="serviceBehaviour">
<endpoint address="" binding="webHttpBinding" contract="StudentCardStatusData.IReceiveData" behaviorConfiguration="web"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehaviour">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="webHttpBinding_IReceiveData" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>
</webHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:1318/ReceiveData.svc" binding="webHttpBinding" bindingConfiguration="webHttpBinding_IReceiveData" contract="IReceiveData" name="webHttpBinding_IReceiveData"/>
<!-- endpoint address="..." binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IReceiveData" contract="IReceiveData"
name="BasicHttpBinding_IReceiveData" / -->
</client>
</system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>
</configuration>
Web Service:
IReceiveData:
namespace StudentCardStatusData {
[DataContract]
public class StatusInfo {
private string _Authent;
private string _Campus;
private string _StudentID;
private string _EnrolmentEndDate;
private string _CardStatus;
private string _SuspendedDate;
private string _OrderedDate;
private string _ReprintDate;
[DataMember(Name="AuthenticationToken")]
public string AuthenticationToken {
get { return _Authent; }
set { _Authent = value; }
}
[DataMember(Name="Campus")]
public String Campus {
get { return _Campus; }
set { _Campus = value; }
}
[DataMember(Name="StudentID")]
public String StudentID {
get { return _StudentID; }
set { _StudentID = value; }
}
[DataMember(Name="EnrolmentEndDate")]
public String EnrolmentEndDate {
get { return _EnrolmentEndDate; }
set { _EnrolmentEndDate = value; }
}
[DataMember(Name="CardStatus")]
public String CardStatus {
get { return _CardStatus; }
set { _CardStatus = value; }
}
[DataMember(Name="SuspendedDate")]
public String SuspendedDate {
get { return _SuspendedDate; }
set { _SuspendedDate = value; }
}
[DataMember(Name = "OrderedDate")]
public String OrderedDate {
get { return _OrderedDate; }
set { _OrderedDate = value; }
}
[DataMember(Name = "ReprintDate")]
public String ReprintDate {
get { return _ReprintDate; }
set { _ReprintDate = value; }
}
}
[ServiceContract]
public interface IReceiveData {
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "ReceiveCardStatusInfo")]
Stream ReceiveCardStatusInfo(Stream request);
}
}
ReceiveData.svc:
namespace StudentCardStatusData {
public class ReceiveData : IReceiveData {
public Stream ReceiveCardStatusInfo(Stream request) {
Stream res = new MemoryStream();
StreamWriter sw = new StreamWriter(res);
try {
ConnectionStringSettings _DefaultSetting = ConfigurationManager.ConnectionStrings["Take2"];
SqlConnection cnn = new SqlConnection(_DefaultSetting.ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
//
if (request != null) {
StreamReader sr = new StreamReader(request);
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<StatusInfo> allitems = serializer.Deserialize<List<StatusInfo>>(sr.ReadToEnd());
bool isFirst = true;
foreach (var item in allitems) {
if (isFirst) {
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT Cast(AuthenticationKey as varchar(50)) FROM IDCardAuthentication";
cmd.Connection.Open();
object o = cmd.ExecuteScalar();
cmd.Connection.Close();
if ((string)o != item.AuthenticationToken.ToUpper()) {
sw.Write("[{\"Result\":\"Undefined Failure\"}]");
return res;
}
isFirst = false;
}
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "dbo.spSaveStudentCardStatus";
cmd.Parameters.Add(new SqlParameter("#Campus", item.Campus));
cmd.Parameters.Add(new SqlParameter("#PerID", item.StudentID));
cmd.Parameters.Add(new SqlParameter("#EndDate", item.EnrolmentEndDate));
cmd.Parameters.Add(new SqlParameter("#Status", item.CardStatus));
cmd.Parameters.Add(new SqlParameter("#Upload", item.SuspendedDate));
cmd.Parameters.Add(new SqlParameter("#Ordered", item.OrderedDate));
cmd.Parameters.Add(new SqlParameter("#Reprint", item.ReprintDate));
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
sw.Write("[{\"Result\":\"Success\"}]");
return res;
}
catch (Exception ex) {
sw.Write("[{\"Result\":\"" + ex.Message + "\"}]");
return res;
}
}
}
}
Web.Config:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="Take2"
connectionString="..."
providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="StudentCardStatusData.ReceiveData" behaviorConfiguration="StudentCardStatusData.ReceiveDataBehavior">
<endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" contract="StudentCardStatusData.IReceiveData" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="https://localhost:1318/ReceiveData.svc" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="StudentCardStatusData.ReceiveDataBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>
</webHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Very first requirement to consume any service is that “Service is Up and Running on Service” here in local ISS in your case.
The reason for getting "Bad Request", or a "Not Found" error when invoking the service is possibility that it is not running on server (localhost).
Are you able to view service page from browser by HTTP request of page "ReceiveData.svc" on your endpoints.
If not then you have to make sure that your service is all ready running before you start consuming it.
As you said that you are running it from same solutions, I am sure you are stating multiple application at the same time. I mean that the Service Application and Consuming Application.
If not you can run multiple start up application from same solution by settings in
Go to Solution properties -> Common properties -> Start up Project and select Multiple start up projects.
So now when you run the solution your both application will start and you should be able to use service.
EDIT
I created test application with all your given code..!!
And it gave me same error..!!!!
So I changed;
request.ContentType = "'text/json; charset=utf-8'";
and it worked..!!! ;)
So please try that.
Hope it helps..!!
I am trying to create a JSON WCF web service.
I'm totally unclear on the whole process really! I'm connecting to MySQL DB on my Server.
So I have the following code:
My Interface -
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/GetAllResources")]
List<Resources> GetAllResources();
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/AddRoom")]
void AddRoom(string location, string name);
...
My Service -
[ScriptService]
public class Service1 : IService1
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void AddRoom(string location, string name)
{
String conString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString"].ConnectionString;
using (MySqlConnection cnn = new MySqlConnection(conString))
{
cnn.Open();
String sql = String.Format("INSERT INTO rooms(roomLocation, roomName) VALUES ({0}, {1});", location, name);
MySqlCommand cmd = new MySqlCommand(sql, cnn);
//doesn't return any rows
cmd.ExecuteNonQuery();
}
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Resources> GetAllResources()
{
String conString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString"].ConnectionString;
List<Resources> al = new List<Resources>();
using (MySqlConnection cnn = new MySqlConnection(conString))
{
cnn.Open();
String sql = String.Format("select * from resources");
MySqlCommand cmd = new MySqlCommand(sql, cnn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
al.Add((Resources)reader[0]);
}
return al;
}
}
...
Web Config -
...
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="5000"/>
</webServices>
</scripting>
</system.web.extensions>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<services>
<service name="RoomBookingService.Service1" behaviorConfiguration="RoomBookingServiceBehavior">
<endpoint address="../Service1.svc"
binding="webHttpBinding"
contract="RoomBookingService.IService1"
behaviorConfiguration="webBehaviour" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="RoomBookingServiceBehavior">
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webBehaviour">
<webHttp automaticFormatSelectionEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
...
Is this correct?? What tools can I use to test the service? I have dropped it onto the server and tried downloading a few testing tools but they don't give me any errors just that it's not returning JSON?!
I will be creating an Android app to talk to the Service, but as this will also be a learning curve I want to know that my service works correctly before adding in another layer of complexity.
Any help or comments on my code or my issue would be greatly appreciated.
Thank you for your time
I managed to get it working:
Here is my code:
Contract:
namespace RoomBookingService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetAllResources")]
String GetAllResources();
Service
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String GetAllResources()
{
String conString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString"].ConnectionString;
List<Dictionary<string, object>> tableRows = new List<Dictionary<string, object>>();
Dictionary<string, object> row= new Dictionary<string,object>();
DataTable dt = new DataTable();
System.Web.Script.Serialization.JavaScriptSerializer serializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
try
{
using (MySqlConnection cnn = new MySqlConnection(conString))
{
cnn.Open();
String sql = String.Format("select resourceID, resourceName, resourceDesc, roomID from resources");
MySqlCommand cmd = new MySqlCommand(sql, cnn);
MySqlDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<String, Object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
tableRows.Add(row);
}
return serializer.Serialize(tableRows);
}
}
catch (Exception ex)
{
return ex.ToString();
}
}
WebConfig
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="5000"/>
</webServices>
</scripting>
</system.web.extensions>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<services>
<service name="RoomBookingService.Service1" behaviorConfiguration="RoomBookingServiceBehavior">
<endpoint address=""
binding="webHttpBinding"
contract="RoomBookingService.IService1"
behaviorConfiguration="webBehaviour" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="RoomBookingServiceBehavior">
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webBehaviour">
<webHttp automaticFormatSelectionEnabled="true"/>
</behavior>
</endpointBehaviors>
Still not absultely clear on everything but it's working!! So I'll go with that :-)
Thanks!
I'm not getting the output in JSON Format. Here is the code
---- IService1.cs ----
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "currency")]
List<Employee> GetAllEmployeesMethod();
[OperationContract]
string TestMethod();
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "players")]
List<Person> GetPlayers();
}
---- Service1.svc.cs ----
public List<Employee> GetAllEmployeesMethod()
{
List<Employee> mylist = new List<Employee>();
using (SqlConnection conn = new SqlConnection("--connection string--"))
{
conn.Open();
string cmdStr = String.Format("Select customercode,CurrencyCode,CurrencyDesc from Currency");
SqlCommand cmd = new SqlCommand(cmdStr, conn);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
mylist.Add(new Employee(rd.GetInt32(0), rd.GetString(1), rd.GetString(2)));
}
conn.Close();
}
return mylist;
}
---- web.config ----
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<authentication mode="Windows"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
</system.web>
<system.webServer>
<directoryBrowse enabled="true"/>
</system.webServer>
<system.serviceModel>
<services>
<service name="JSONSerialization.Service1" behaviorConfiguration="EmpServiceBehaviour">
<!-- Service Endpoints -->
<endpoint address="" binding="webHttpBinding" contract="JSONSerialization.IService1" behaviorConfiguration="web" >
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="EmpServiceBehaviour">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json" helpEnabled="true" defaultBodyStyle="Bare"/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
and when I run this service, I get the data in
but I want the result to be in JSON format
Example: {"currencycode":"INR","DESCRIPTION":"Indian Rupees","customercode" : "1001"},....
add [Serialize] attribute to your methods
I use visual studio 11 to add service (Add service Reference).
When I added the service Article, I have An articleClient with one constructor:
public RssArticleServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
How can I use this constructor, i don't know which value of binding should I use??
Any example or sample please??
Merci
Best regards
I do this:
BasicHttpSecurityMode securitymode = BasicHttpSecurityMode.Transport; BasicHttpBinding binding = new BasicHttpBinding(securitymode); binding.MaxReceivedMessageSize = int.MaxValue; binding.MaxBufferSize = int.MaxValue; Uri uri = new Uri("adresse/RssArticleService.svc";); _clientArticles = new RssArticleServiceClient(binding, new EndpointAddress("adresse/RssArticleService.svc";)); var result=await _clientArticles.GetRssDataAsync("1", "fr");
And A cath this error:
**here was no endpoint listening at adresse/RssArticleService.svc that could accept the message. This is often caused by an incorrect address or SOAP**
What can i do, should i change the type of binding??
This is my implementation :
BasicHttpSecurityMode securitymode = HostSource.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase) ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.None;
BasicHttpBinding binding = new BasicHttpBinding(securitymode);
binding.MaxReceivedMessageSize = int.MaxValue;
binding.MaxBufferSize = int.MaxValue;
Uri uri = new Uri(Application.Current.Host.Source, "../service.svc");
_client = new RssArticleServiceClient(binding, new EndpointAddress(uri))
EDIT : you need to add this in your web.config :
<system.serviceModel>
<services>
<service name="namespace.RssArticleService"
behaviorConfiguration="RssArticleServiceBehavior">
<endpoint address=""
binding="basicHttpBinding"
contract="namespace.IRssArticleService"/>
</service>
</services>
<serviceBehaviors>
<behavior name="RssArticleServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>