REST Web service not working, - c#

Hello there i share my code please tell me why my code is not work . I am very new to this REST web service i just started to writing this. so give some solution to the below mention code.
This is my webservices.cs code
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.Data;
namespace webservice_PCCFWL
{
[ServiceContract]
public interface IWebServices
{
[OperationContract]
[WebInvoke(UriTemplate = "/get_userauthentication/{username}/{password}",Method ="GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
List<userloginretrive> getuserdetails(string username,string password);
}
[DataContract]
public class userloginretrive
{
public userloginretrive()
{
uname = null;
udesignation = null;
division = null;
ranger = null;
}
[DataMember(Name = "uname", Order = 1)]
public string uname { get; set; }
[DataMember(Name = "udesignation", Order = 2)]
public string udesignation { get; set; }
[DataMember(Name = "division", Order = 3)]
public string division { get; set; }
[DataMember(Name = "ranger", Order = 4)]
public string ranger { get; set; }
}
}
=========================
This is my .cs code
using System;
using System.Collections.Generic;
using System.Web.Security;
using System.Security.Cryptography;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace webservice_PCCFWL
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "WebServices" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select WebServices.svc or WebServices.svc.cs at the Solution Explorer and start debugging.
public class WebServices : IWebServices
{
string myKey;
TripleDESCryptoServiceProvider cryptDES3 = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider cryptMD5Hash = new MD5CryptoServiceProvider();
public WebServices()
{
myKey = "kt763g-kj_7gfhd7GJD-563bjf";
}
private string EncryptUser(string myString)
{
cryptDES3.Key = cryptMD5Hash.ComputeHash(ASCIIEncoding.ASCII.GetBytes(myKey));
cryptDES3.Mode = CipherMode.ECB;
ICryptoTransform desdencrypt = cryptDES3.CreateEncryptor();
var MyASCIIEncoding = new ASCIIEncoding();
byte[] buff = ASCIIEncoding.ASCII.GetBytes(myString);
return Convert.ToBase64String(desdencrypt.TransformFinalBlock(buff, 0, buff.Length));
}
public List<userloginretrive> getuserdetails(string username,string password)
{
List<userloginretrive> objlist = new List<userloginretrive>();
string pass = EncryptUser(password);
try
{
SqlParameter[] para = new SqlParameter[]
{
new SqlParameter("#p_login_id",username),
new SqlParameter("#p_password",pass)
};
using (DataTable dt = SQLHelper.DataAcessLayer.SqlHelper.ExecuteDataTable(sql.Connection.Configuration.ConnectionString, CommandType.Text, "select User_Name,User_Designation,Wl_Division,Wl_Range from UserDetails where User_LoginId=#p_login_id and User_Password=#p_password", para))
{
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
objlist.Add(new userloginretrive
{
uname = Convert.ToString(dr["User_Name"]),
udesignation = Convert.ToString(dr["User_Designation"]),
division = Convert.ToString(dr["Wl_Division"]),
ranger = Convert.ToString(dr["Wl_Range"])
});
}
}
else
{
objlist.Add(new userloginretrive
{
uname = "no",
udesignation = "no",
division = "no",
ranger = "no"
});
}
}
}
catch (Exception ex)
{
throw ex;
}
return objlist;
}
}
}
======================
This is my webconfig file
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
<add key="myConnectionString"
value="Data Source=localhost;Initial Catalog=PCCFWL;uid=sa;pwd=sparc_123;Pooling=false;MINPOOLSIZE=20;MAXPOOLSIZE=1000;"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehaviors">
<!-- 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="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="serviceBehaviors" name="webservice_PCCFWL.WebServices">
<endpoint address="WebServices.svc" contract="webservice_PCCFWL.IWebServices" binding="webHttpBinding" behaviorConfiguration="web"></endpoint>
<endpoint address="" contract="IMetadataExchange" binding="mexHttpBinding"></endpoint>
</service>
</services>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="ApplicationInsightsWebTracking"/>
<remove name="TelemetryCorrelationHttpModule"/>
<add name="TelemetryCorrelationHttpModule"
type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation"
preCondition="integratedMode,managedHandler"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
preCondition="managedHandler"/>
</modules>
<!--
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>
Please give some solution . my program is running the only first page of service opening then nothing happening. so please help me here.

Related

HttpModule in WCF project just works once

Please consider this code:
<system.web>
<compilation debug="true" targetFramework="4.6"/>
<httpRuntime targetFramework="4.5.2"/>
<authentication mode="None" />
</system.web>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="MyNameSpace.Services.Service1" behaviorConfiguration="ServiceBehavior">
<endpoint binding="basicHttpBinding" contract="MyNameSpace.Services.ISrv"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpBinding" scheme="http"/>
</protocolMapping>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="AuthSecurity" type="MyNameSpace.CustomAuthorization" />
</modules>
<directoryBrowse enabled="true"/>
</system.webServer>
and the HttpModule code is:
namespace MyNameSpace
{
public class CustomAuthorization : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
CheckAccess();
}
private bool CheckAccess()
{
HttpContext c = HttpContext.Current;
if (HttpContext.Current.Handler != null) // <--Break Point
{
string authHeader = HttpContext.Current.Request.Headers["Authorization"];
...
}
return false;
}
}
}
and in the client I wrote this code:
Service1client client = new Service1client();
client.ClientCredentials.UserName.UserName = "mmmm"
client.ClientCredentials.UserName.Password = "nnnn";
var tmp = client.DoWork(1);
the problem is after running the project, Service returns the correct result but HttpModule code didn't execute.
When I use a breakpoint in HttpModule it hits during Application_Start event. But after that it doesn't hit any more and its code doesn't execute.
Where is the problem?
Thanks
As I understand it, you defined just what to do at application start; if you want to check incoming requests, try to add these methods to your HttpModule and set breakpoints to check whether those methods are hit:
private void Application_BeginRequest(Object source,
EventArgs e)
{
CheckAccess();
}
private void Application_EndRequest(Object source, EventArgs e)
{
CheckAccess();
}
Of course you need to register those methods at application start:
application.BeginRequest +=
(new EventHandler(this.Application_BeginRequest));
application.EndRequest +=
(new EventHandler(this.Application_EndRequest));

How to limit secure protocol in wcf service

I need to write WCF service using TLS 1.2.I need to use only this security protocol and (as i think) refuse connections with other secure protocol types. I have created certificate. Bind it to port. Https works well. I read everywhere that i need to write next string of code:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Ok, i wrote it, but had no effect. Service side code:
using System;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Net;
using System.ServiceModel;
using System.Runtime.Serialization;
using static System.Console;
namespace ConsoleHost
{
public class DistributorValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
throw new SecurityTokenException("Both username and password required");
if (userName != "login" || password != "pass")
throw new FaultException($"Wrong username ({userName}) or password ");
}
}
public class Service1 : IService1
{
public string GetData(int value)
{
return $"You entered: {value}";
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException(nameof(composite));
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
}
[DataContract]
public class CompositeType
{
[DataMember]
public bool BoolValue { get; set; } = true;
[DataMember]
public string StringValue { get; set; } = "Hello ";
}
class Program
{
static void Main(string[] args)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServiceHost host = new ServiceHost(typeof(Service1));
host.Open();
WriteLine("Press any key to stop server...");
ReadLine();
}
}
}
App.config contains:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<system.serviceModel>
<services>
<service name="ConsoleHost.Service1">
<host>
<baseAddresses>
<add baseAddress = "https://localhost:8734/Service1/" />
</baseAddresses>
</host>
<endpoint address="" binding="wsHttpBinding" contract="ConsoleHost.IService1" bindingConfiguration="securityBinding">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="securityBinding">
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" />
<message clientCredentialType="UserName" />
<!--establishSecurityContext="false" />-->
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ConsoleHost.DistributorValidator,ConsoleHost"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Client side code:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
Service1Client client = new Service1Client();
client.ClientCredentials.UserName.UserName = "login";
client.ClientCredentials.UserName.Password = "pass";
Console.WriteLine(client.GetData(10));
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
if (ex.InnerException != null)
{
Console.WriteLine("Inner: " + ex.InnerException.Message);
if (ex.InnerException.InnerException != null)
Console.WriteLine("Inner: " + ex.InnerException.InnerException.Message);
}
}
Console.ReadLine();
}
}
}
As you can see on service side i have set security protocol to Tls 1.2. On client side i have set security protocol to Ssl3. I am waiting that service will refuse client connection, because server must work and accept clients who will work with only Tls 1.2 security protocol. But i'm not getting this result. Client connects and works well. What's the problem?
I understand that i can change some settings on IIS to use only Tls 1.2. But i am making self hosting wcf service and that's the problem.
It can't be done for server using ServicePointManager.SecurityProtocol option, that's used to connection to sth through a specific security protocol. You can't turn off some security protocol for an separate application, you able to allow or dissallow connections for whole server. If u want disable all protocols except TLS 1.2 u have to open registry windows and find out the next key:
HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\
And set the next values for each protocol in key [Server]: DisabledByDefault = 1, Enabled = 0
How to enable TLS

Missing contract in WCF self hosted console application

Trying to make simple selfhosted WCF service in console application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace SupportSrvWCF
{
[ServiceContract]
public interface IA
{
[OperationContract]
int LogIt(int id, string data, ref int level);
}
public class SupportServicee : IA
{
public int LogIt(int id, string data, ref int level)
{
return 0;
}
}
class Program
{
static void Main(string[] args)
{
try
{
ServiceHost selfHost = new ServiceHost(typeof(SupportServicee));
selfHost.Open();
Console.WriteLine("The service is running. Press any key to stop.");
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine("An error occurred: '{0}'", e);
}
}
}
}
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<services>
<service name="SupportSrvWCF.SupportServicee">
<endpoint address="" binding="basicHttpBinding" contract="SupportSrvWCF.IA ">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8002/WCFService1" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<!--<behavior name="CalculatorServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>-->
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>
Have exception:
An error occurred: 'System.InvalidOperationException: The contract name 'Support
SrvWCF.IA ' could not be found in the list of contracts implemented by the servi
ce 'SupportServicee'.
Where is problem
hello try the following code instead and delete the service configuration from app.config
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace SupportSrvWCF
{
[ServiceContract]
public interface IA
{
[OperationContract]
int LogIt(int id, string data, ref int level);
}
public class SupportServicee : IA
{
public int LogIt(int id, string data, ref int level)
{
return 0;
}
}
class Program
{
static void Main(string[] args)
{
using (ServiceHost selfHost = new ServiceHost(typeof(SupportServicee),new Uri("http://localhost:8080/Myservice")))
{
try
{
selfHost.AddServiceEndpoint(typeof(IA),new BasicHttpBinding(),"basic");
selfHost.Open();
Console.WriteLine("The service is running. Press any key to stop.");
Console.ReadKey();
}
catch (Exception e)
{
Console.WriteLine("An error occurred: '{0}'", e);
}
}
}
}
}

WCF Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata

I have a WebService that intents to upload a file to a server but i keep getting the error in the title when i want to run it from my VS2010.
I have searched over this site and the solutions have not helped me, unless i'm doing something wrong.
this is the site that i get the example: Example
here is my Interface
namespace FUWcf
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
public class FileUploadService : IFileUploadService
{
public bool UploadFileData(FileData fileData)
{
bool result = false;
try
{
//Set the location where you want to save your file
string FilePath = Path.Combine(ConfigurationManager.AppSettings["Path"], fileData.FileName);
//If fileposition sent as 0 then create an empty file
if (fileData.FilePosition == 0)
{
File.Create(FilePath).Close();
}
//Open the created file to write the buffer data starting at the given file position
using (FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
fileStream.Seek(fileData.FilePosition, SeekOrigin.Begin);
fileStream.Write(fileData.BufferData, 0, fileData.BufferData.Length);
}
}
catch (Exception ex)
{
ErrorDetails ed = new ErrorDetails();
ed.ErrorCode = 1001;
ed.ErrorMessage = ex.Message;
throw new FaultException<ErrorDetails>(ed);
}
return result;
}
}
}
Here is the service:
namespace FUWcf
{
// 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 IFileUploadService
{
[OperationContract]
[FaultContract(typeof(ErrorDetails))]
bool UploadFileData(FileData fileData);
}
[DataContract]
public class FileData
{
[DataMember]
public string FileName { get; set; }
[DataMember]
public byte[] BufferData { get; set; }
[DataMember]
public int FilePosition { get; set; }
}
[DataContract]
public class ErrorDetails
{
[DataMember]
public int ErrorCode { get; set; }
[DataMember]
public string ErrorMessage { get; set; }
}
}
And here is my web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<appSettings>
<add key="Path" value="C:\Users\c.asacha\Documents\Proyectos\Generales\FUWcf\FUWcf\temp\"/>
</appSettings>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHBBinding" />
</wsHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="fus" name="FUWcd.FileUploadService">
<endpoint address=""
binding="wsHttpBinding" bindingConfiguration="WSHBBinding" name="FileUploadService"
contract="FUWcf.IFileUploadService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="fus">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="false" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
I hope someone can help me with this, or a link for a better example.
Thanks in advance.
You configuration is wrong ( Service name is name="FUWcd.FileUploadService" where it should be name="FUWcf.FileUploadService")
Anyway- Created the web site and added the web service like this ( You dont need Mex endpoint in web configuration as it is already on, The url will become the servicename http://{localServerName}:{port}/FileUploadService.svc):
public class FileUploadService : IFileUploadService
{
public bool UploadFileData(FileData fileData)
{
bool result = false;
try
{
//Set the location where you want to save your file
string FilePath = Path.Combine(ConfigurationManager.AppSettings["Path"], fileData.FileName);
//If fileposition sent as 0 then create an empty file
if (fileData.FilePosition == 0)
{
File.Create(FilePath).Close();
}
//Open the created file to write the buffer data starting at the given file position
using (FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
fileStream.Seek(fileData.FilePosition, SeekOrigin.Begin);
fileStream.Write(fileData.BufferData, 0, fileData.BufferData.Length);
}
}
catch (Exception ex)
{
ErrorDetails ed = new ErrorDetails();
ed.ErrorCode = 1001;
ed.ErrorMessage = ex.Message;
throw new FaultException<ErrorDetails>(ed);
}
return result;
}
}
Data Contracts were same as well.
Then in Web.Config file added like this and it works fine:
<system.serviceModel>
<services>
<service name="WebApplication1.FileUploadService">
<endpoint address="fileService" binding="wsHttpBinding" bindingConfiguration=""
contract="WebApplication1.IFileUploadService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />

Deserialize JSON object sent from Android app to WCF webservice

I'm trying to send a JSON object to my webservice method, the method is defined like this:
public String SendTransaction(string trans)
{
var json_serializer = new JavaScriptSerializer();
Transaction transObj = json_serializer.Deserialize<Transaction>(trans);
return transObj.FileName;
}
Where I want to return the FileName of this JSON string that I got as a parameter.
The code for the android application:
HttpPost request = new HttpPost(
"http://10.118.18.88:8080/Service.svc/SendTransaction");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// Build JSON string
JSONStringer jsonString;
jsonString = new JSONStringer()
.object().key("imei").value("2323232323").key("filename")
.value("Finger.NST").endObject();
Log.i("JSON STRING: ", jsonString.toString());
StringEntity entity;
entity = new StringEntity(jsonString.toString(), "UTF-8");
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
entity.setContentType("application/json");
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity httpEntity = response.getEntity();
String xml = EntityUtils.toString(httpEntity);
Log.i("Response: ", xml);
Log.d("WebInvoke", "Status : " + response.getStatusLine());
I only get a long html file out, which tells me The server has encountered an error processing the request. And the status code is HTTP/1.1 400 Bad Request
My Transaction class is defined in C# like this:
[DataContract]
public class Transaction
{
[DataMember(Name ="imei")]
public string Imei { get; set; }
[DataMember (Name="filename")]
public string FileName { get; set; }
}
How can I accomplish this in the right way?
EDIT, this is my web.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="httpBehavior">
<webHttp />
</behavior >
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<!-- 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>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
<services>
<service name="Service.Service">
<endpoint address="" behaviorConfiguration="httpBehavior" binding="webHttpBinding" contract="Service.IService"/>
</service>
</services>
<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>
</configuration>
#Tobias, This is not an answer. But since it was a little bit long for comment, I post it here. Maybe it can help to diagnose your problem. [A full working code].
public void TestWCFService()
{
//Start Server
Task.Factory.StartNew(
(_) =>{
Uri baseAddress = new Uri("http://localhost:8080/Test");
WebServiceHost host = new WebServiceHost(typeof(TestService), baseAddress);
host.Open();
},null,TaskCreationOptions.LongRunning).Wait();
//Client
var jsonString = new JavaScriptSerializer().Serialize(new { xaction = new { Imei = "121212", FileName = "Finger.NST" } });
WebClient wc = new WebClient();
wc.Headers.Add("Content-Type", "application/json");
var result = wc.UploadString("http://localhost:8080/Test/Hello", jsonString);
}
[ServiceContract]
public class TestService
{
[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
public User Hello(Transaction xaction)
{
return new User() { Id = 1, Name = "Joe", Xaction = xaction };
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public Transaction Xaction { get; set; }
}
public class Transaction
{
public string Imei { get; set; }
public string FileName { get; set; }
}
}

Categories

Resources