How to pass multiple parameter in wcf restful service? - c#

IService.cs
[OperationContract]
[WebGet(UriTemplate = "/IsValidUser?userid={userid}&password={password}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string IsValidUser(string userid, string password);
Service.cs
public string IsValidUser(string userid, string password)
{
if (userid =="bob" && password =="bob")
{
return "True";
}
else
{
return "false";
}
}
web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
</system.web>
<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServBehave">
<!--Endpoint for REST-->
<endpoint address="rest" binding="webHttpBinding" behaviorConfiguration="restPoxBehavior" contract="IService"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServBehave">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<!--Behavior for the REST endpoint for Help enability-->
<behavior name="restPoxBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Problem:
Here my problem is that I want to pass multiple parameter while calling a WCF rest service, but I am not able to pass multiple parameters to that WCF rest service. I want to pass userid and password and check for in it. If it is bob then allow to go ahead.
And when I am calling this url:
http://localhost:48401/ARService/Service.svc/rest/IsValidUser?userid=bob&password=bob
then I am getting this error on my web page:
Endpoint not found. Please see the service help page for constructing valid requests to the service.
If somebody have idea how to call IsValidUser in my case with this function parameter. Please help me.

you can write this way:
Iservice.cs
[OperationContract]
[WebGet(UriTemplate = "IsValidUser/{userid}/{password}")]
string IsValidUser(string userid, string password);
service .cs
public string IsValidUser(string userid, string password)
{
if (userid== "root" && password== "root")
{
return "True";
}
else
{
return "false";
}
}
Run this Url in Browser,then you will get output
localhost/service.svc/rest/IsValidUser/root/root

try this
[OperationContract]
[WebGet(UriTemplate = "IsValidUser?userid={userid}&password={password}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string IsValidUser(string userid, string password);

Add BodyStyle on OperationContract
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]

Related

WCF Service Method is not Working

I am currently working on wcf service and Service is running localhost.I have some methods in Wcf Service. I am facing some Errors when I want to access the method from localhost by typing for example http://localhost:50028/StudentService.svc/GetAllStudent/
its shows following errors.
**
Request Error
The server encountered an error processing the request. Please see the service help page for constructing valid requests to the service.
**
Here is my code form Wcf service....
[ServiceContract]
public interface IStudentService
{
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetAllStudent/")]
List<StudentDataContract> GetAllStudent();
[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetStudentDetails/{StudentId}")]
StudentDataContract GetStudentDetails(string StudentId);
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/AddNewStudent")]
bool AddNewStudent(StudentDataContract student);
[OperationContract]
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/UpdateStudent")]
void UpdateStudent(StudentDataContract contact);
[OperationContract]
[WebInvoke(Method = "DELETE",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "DeleteStudent/{StudentId}")]
void DeleteStudent(string StudentId);
}
}
Here is my code of Implementation ...
public class StudentService : IStudentService
{
StudentManagementEntities ctx;
public StudentService()
{
ctx = new StudentManagementEntities();
}
public List<StudentDataContract> GetAllStudent()
{
//if (HttpContext.Current.Request.HttpMethod == "GetAllStudent")
// return null;
var query = (from a in ctx.Students
select a).Distinct();
List<StudentDataContract> studentList = new List<StudentDataContract>();
query.ToList().ForEach(rec =>
{
studentList.Add(new StudentDataContract
{
StudentID = Convert.ToString(rec.StudentID),
Name = rec.Name,
Email = rec.Email,
EnrollYear = rec.EnrollYear,
Class = rec.Class,
City = rec.City,
Country = rec.Country
});
});
return studentList;
}
public StudentDataContract GetStudentDetails(string StudentId)
{
StudentDataContract student = new StudentDataContract();
try
{
int Emp_ID = Convert.ToInt32(StudentId);
var query = (from a in ctx.Students
where a.StudentID.Equals(Emp_ID)
select a).Distinct().FirstOrDefault();
student.StudentID = Convert.ToString(query.StudentID);
student.Name = query.Name;
student.Email = query.Email;
student.EnrollYear = query.EnrollYear;
student.Class = query.Class;
student.City = query.City;
student.Country = query.Country;
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
return student;
}
public bool AddNewStudent(StudentDataContract student)
{
try
{
Student std = ctx.Students.Create();
std.Name = student.Name;
std.Email = student.Email;
std.Class = student.Class;
std.EnrollYear = student.EnrollYear;
std.City = student.City;
std.Country = student.Country;
ctx.Students.Add(std);
ctx.SaveChanges();
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
return true;
}
public void UpdateStudent(StudentDataContract student)
{
try
{
int Stud_Id = Convert.ToInt32(student.StudentID);
Student std = ctx.Students.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();
std.Name = student.Name;
std.Email = student.Email;
std.Class = student.Class;
std.EnrollYear = student.EnrollYear;
std.City = student.City;
std.Country = student.Country;
ctx.SaveChanges();
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
}
public void DeleteStudent(string StudentId)
{
try
{
int Stud_Id = Convert.ToInt32(StudentId);
Student std = ctx.Students.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();
ctx.Students.Remove(std);
ctx.SaveChanges();
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
}
}
}
Here is the web.config file ..
<?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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5" />
</system.web>
<system.serviceModel>
<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>
<webHttp helpEnabled="True"/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="webHttpBinding" scheme="http" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true" />
</system.webServer>
<connectionStrings>
<add name="StudentManagementEntities" connectionString="metadata=res://*/SchoolManagement.csdl|res://*/SchoolManagement.ssdl|res://*/SchoolManagement.msl;provider=System.Data.SqlClient;provider connection string="data source=KHUNDOKARNIRJOR\KHUNDOKERNIRJOR;initial catalog=Student;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>
I can not access the from localhost its is always shows this error
Request Error
The server encountered an error processing the request. Please see the service help page for constructing valid requests to the service.
Here is Screen shot
Please any help will be highly appreciated..
I don't see "services" element in your config file. Please take a look at the below link to configure your service.
Configuring Services
Another method is to create a wcf service using visual studio. Visual studio will generate appropriate config file for you. Then you can replace the methods, interface and configuration accordingly.
I see that you are trying to return a List. I don't think you can pass List as return parameter.
Please check all methods on "
http://localhost:50028/StudentService.svc" another suggestion, please
remove "/" from uriTemplate. Just write "GetAllStudent" instead of
"/GetAllStudent/".
> <services>
> <service name="" behaviorConfiguration="serviceBehavior">
> <endpoint address="" binding="webHttpBinding" contract="" behaviorConfiguration="web"/>
> </service>
> </services>
> <behaviors>
> <serviceBehaviors>
> <behavior name="serviceBehavior">
> <serviceMetadata httpGetEnabled="true"/>
> <serviceDebug includeExceptionDetailInFaults="false"/>
> </behavior>
> </serviceBehaviors>
> <endpointBehaviors>
> <behavior name="web">
> <webHttp/>
> </behavior>
> </endpointBehaviors>
> </behaviors>
As I look there is service and behaviors tags are missing from webconfig.

WCF Service not receiving data in POST

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!

JSON C# Web Service Creation and Testing?

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!

Not getting service result in Json Format?

IService.cs
//it is working fine with Xml
[OperationContract]
[WebGet(UriTemplate = "/PrintProductCategory",RequestFormat=WebMessageFormat.Xml,ResponseFormat = WebMessageFormat.Xml)]
List<ProductCategory> GetProductCategory();
//it is not working with Json
[OperationContract]
[WebGet(UriTemplate = "/Print",RequestFormat=WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
List<ProductCategory> GetProductCategory();
Service.cs
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service : IService
{
ARserviceEntities de = new ARserviceEntities();
public List<ProductCategory> GetProductCategory()
{
var procat = from t in de.ProductCategories select t;
return procat.ToList();
}
}
web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Data.Entity.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</assemblies>
<buildProviders>
<add extension=".edmx" type="System.Data.Entity.Design.AspNet.EntityDesignerBuildProvider" />
</buildProviders>
</compilation>
</system.web>
<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServBehave">
<!--Endpoint for REST-->
<endpoint address="rest" binding="webHttpBinding" behaviorConfiguration="restPoxBehavior" contract="IService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServBehave">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<!--Behavior for the REST endpoint for Help enability-->
<behavior name="restPoxBehavior">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<connectionStrings>
<add name="ARserviceEntities" connectionString="metadata=res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=GOVINDA-PC;initial catalog=ARservice;persist security info=True;user id=sa;password=sa_12345;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Explanation :
Here my rest service working fine with XML.But when i am using ResponseFormat = WebMessageFormat.Json then i am getting error on webpage is that No data recived.
But it is workig fine with XML.so please help for this problem where i am doing mistake.
You could try using fiddler to actually see what is going on HTTP-traffic-wise. See http://fiddler2.com/.
I had this working on one of my recent projects, just checked my config and I can't see anything obviously different with yours. Only thing I can see that’s different (bit of a long shot) is that I’ve specified the [WebGet] attribute on the concrete class implementation, and used [WebInvoke]
So IService.cs would become..
[OperationContract]
List<ProductCategory> GetProductCategory();
and Service.cs would be..
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service : IService
{
ARserviceEntities de = new ARserviceEntities();
[WebInvoke(UriTemplate = "/Print", Method = "GET", ResponseFormat = WebMessageFormat.Json)]
public List<ProductCategory> GetProductCategory()
{
var procat = from t in de.ProductCategories select t;
return procat.ToList();
}
}
Can't see why it would make a difference, but might be worth trying!
I could that what is problem in my case.
IService.cs
[OperationContract]
[WebGet(UriTemplate = "/Print",RequestFormat=WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
List<ProductCategory> GetProductCategory();
Service.cs :
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service : IService
{
ARserviceEntities de = new ARserviceEntities();
public List<ProductCategory> GetProductCategory()
{
var procat = from t in de.ProductCategories select t;
return procat.ToList();
}
}
And my XML File was also right.
What was the problem :
problem was that i was using of .EDMX for database.
Solution
I Just use .dbml for database.And I Could solve my problem.
Remark :
Whenever you are making WCF Service in visual studio 2010 then use .dbml instead of .edmx. if you want to retrieve result in json or xmlformat.
If Someone is fencing like my problem so they can try this answer.
I hope it will help someone.

How to get the response and request in JSON format?

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

Categories