这是我的第一个WCF。
我到处寻找但是我无法在足够的水平上阅读英语无法找到解决方案。
如何解决此错误?
我已添加其余代码
Service1.cs:
namespace WcfJsonRestService
{
public class Service1 : IService1
{
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "data/{Data}")]
public DTResult GetData(string Data)
{
DTResult result = new DTResult();
try
{
result.Error = false;
string connectionString = ConfigurationManager.ConnectionStrings["db"].ToString();
DTResponse ResponseData = JsonConvert.DeserializeObject<DTResponse>(DecodeFrom64(Data));
result.DataSet = tvCore.Exec(connectionString, ResponseData.storedProcedure, ResponseData.parameters);
}
catch (Exception e)
{
result.DataSet = null;
result.Error = true;
result.ErrorMsg = e.Message;
}
return result;
}
static public string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}
}
/*
* MSSql Connect Class
*/
public class tvCore
{
static public string Exec(string cntStr, string SP, dynamic[] param)
{
SqlConnection Cnt = new SqlConnection(cntStr);
DataTable Qry = new DataTable();
DataSet DSet = new DataSet();
SqlDataAdapter SqlDataAdp = new SqlDataAdapter();
SqlCommand SqlCmd = new SqlCommand(SP, Cnt);
SqlCmd.CommandType = CommandType.StoredProcedure;
Cnt.Open();
SqlCommandBuilder.DeriveParameters(SqlCmd);
if (param.Length != SqlCmd.Parameters.Count-1)
throw new Exception("Parameters lenght not match.");
SqlCmd.Parameters.RemoveAt(0);
for (int i = 0; i < SqlCmd.Parameters.Count; i++)
if (SqlCmd.Parameters[i].SqlDbType == SqlDbType.DateTime)
SqlCmd.Parameters[i].Value = param[i] == null ? DBNull.Value : DateTime.ParseExact(param[i], "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
else
SqlCmd.Parameters[i].Value = param[i] == null ? DBNull.Value : param[i];
SqlDataReader reader = SqlCmd.ExecuteReader();
//DataTable schema = reader.GetSchemaTable();
//schema.PrimaryKey = new DataColumn[] { schema.Columns["ColumnOrdinal"] };
string result = JsonConvert.SerializeObject(reader, new DTConvert());
reader.Close();
Cnt.Close();
// SqlDataAdp.SelectCommand = SqlCmd;
// SqlDataAdp.FillSchema(DSet, SchemaType.Mapped);
// SqlDataAdp.Fill(Qry);
return result;
}
}
/*
* DataTable To JSon Class
*/
public class DTConvert : JsonConverter
{
public override bool CanConvert(System.Type objectType)
{
//Return objectType = GetType(DataTable)
return typeof(SqlDataReader).IsAssignableFrom(objectType);
}
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
SqlDataReader reader = value as SqlDataReader;
int ncols = reader.FieldCount;
DataTable schema = reader.GetSchemaTable();
writer.WriteStartObject();
#region Columns
writer.WritePropertyName("Columns");
writer.WriteStartArray();
foreach( DataRow col in schema.Rows )
{
writer.WriteStartObject();
string field = "AllowDBNull";
writer.WritePropertyName(field);
writer.WriteValue(col[field]);
field = "IsAutoincrement";
writer.WritePropertyName(field);
writer.WriteValue(col[field]);
field = "ColumnName";
writer.WritePropertyName(field);
writer.WriteValue(col[field]);
field = "DataType";
writer.WritePropertyName(field);
writer.WriteValue((col[field] as Type).Name);
field = "ColumnSize";
writer.WritePropertyName(field);
writer.WriteValue(col[field]);
field = "isReadOnly";
writer.WritePropertyName(field);
writer.WriteValue(col[field]);
field = "isUnique";
writer.WritePropertyName(field);
writer.WriteValue(col[field]);
writer.WriteEndObject();
}
writer.WriteEndArray();
#endregion
#region Rows
writer.WritePropertyName("Rows");
writer.WriteStartArray();
while (reader.Read())
{
writer.WriteStartObject();
for (int i = 0; i < reader.FieldCount; i++)
{
writer.WritePropertyName(reader.GetName(i));
writer.WriteValue(reader[i]);
}
writer.WriteEndObject();
}
writer.WriteEndArray();
#endregion
writer.WriteEndObject();
}
public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
JObject jObject = JObject.Load(reader);
DataTable table = new DataTable();
return table;
}
}
public class DTResult
{
public string DataSet { get; set; }
public bool Error { get; set; }
public string ErrorMsg { get; set; }
}
public class DTResponse
{
public string storedProcedure { get; set; }
public dynamic[] parameters { get; set; }
}
}
的App.config
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="db" connectionString="Server=SERVERNAME;Database=DBNAME;User Id=USERNAME;Password=PASSWORD;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.serviceModel>
<services>
<service name="WcfJsonRestService.Service1">
<endpoint address="http://localhost/iPadWcf"
binding="webHttpBinding"
contract="WcfJsonRestService.IService1"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior>
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
答案 0 :(得分:-1)
我假设您正在寻找一种创建RESTful WebService的方法。 这是一个小帮助,我已经创建了我的一个实践。
如果您有商店,并且愿意获取有关产品的信息,则必须由客户端向WebService发送请求以提供服务。您必须在Web.config中定义一些内容。
在添加
中<services>
<service name="RestService_Production.RestService">
<endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" contract="RestService_Production.IRestService" />
</service>
</services
和
<endpointBehaviors>
<behavior name="web">
<webHttp />
</behavior>
</endpointBehaviors>
假设您有这样的方法
public interface IRestService
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "product/{id}")]
Product GetProductInformations(string id);
}
在.svc中,你必须像这样定义它
public Product GetProductInformations(string id)
{
return new Product();
}
您可以通过
向Rest服务发出请求private static void Main(string[] args)
{
Remote remote = new Remote(endPoint, methodType, methodName, methodData);
string requestUri = remote.GetEndPoint() + remote.GetMethodName() + remote.GetDataPost();
var request = (HttpWebRequest)WebRequest.Create(requestUri);
request.Method = remote.GetMethodType();
request.ContentLength = 0;
request.ContentType = "text/xml";
Console.WriteLine("Wait until the WebService starts and then press a key to continue!");
Console.ReadKey();
try
{
var response = request.GetResponse();
Stream getResponseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(getResponseStream);
string friendlyResponse = GenerateFriendlyJson(sr.ReadToEnd());
var jss = new JavaScriptSerializer();
var product = jss.Deserialize<Dictionary<string, string>>(friendlyResponse);
Console.WriteLine("Name: " + product["Name"] +
", Description: " + product["Description"] +
", Price: " + product["Price"] +
", Quantity: " + product["Quantity"]);
}
catch (WebException wEx)
{
Console.WriteLine("Could not access to network through protocol: \n" + wEx.ToString());
}
catch (Exception cEx)
{
Console.WriteLine("Some common excepion happened: \n" + cEx.ToString());
}
finally
{
Console.ReadKey();
}
}
如果GET methodType是“GET”,“POST”,“PUT”或“DELETE”字符串,则名称类似于“product /”,数据类似于符合字符串的任何内容。 endPoint应如下所示:“ht.tp://(your host):10064 / RestService.svc /”(我不得不改变它,因为SO不允许链接)
我希望它有所帮助。如果您有任何问题,我会将该项目上传到Git或其他东西。