我正在构建一个JSONP服务。
如果我使用System.ServiceModel.Activation.WebScriptServiceHostFactory
,则可以使用。
我需要使用System.ServiceModel.Activation.WebServiceHostFactory
因为我想使用URITemplate所以我可以传递一个参数。当我切换到这个工厂时,它不再将响应编码为jsonp。所以我从我的javascript中得到一个错误,它无法弄清楚如何处理{"isbn": "~1234567890~"}
这是我需要序列化的地方吗?如何将其添加到此c#代码中:
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.IO;
using System.Text;
using System;
using System.Collections;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
using System.Runtime.Serialization.Json;
namespace Microsoft.Samples.Jsonp
{
[DataContract]
public class Response
{
[DataMember]
public string isbn;
}
[ServiceContract(Namespace = "JsonpAjaxService")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CustomerService
{
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public Response GetCustomer()
{
string isbns = "";
/*string line= "";*/
try
{
MySqlConnection sqlConnection1 = new MySqlConnection("Server=localhost; Database=mydb; Uid=peggy; Pwd=dpL'engl3");
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader reader;
cmd.CommandText = "SELECT name, obitdate, page FROM dobits";
/* cmd.CommandType = CommandType.Text;*/
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
while (reader.Read())
{
isbns = isbns + '~' + reader.GetString(0) + '^' + reader.GetString(1) + '#' + reader.GetString(2);
}
sqlConnection1.Close();
}
catch (Exception e)
{
System.IO.Directory.CreateDirectory(@"c:\data\exception");
Console.WriteLine("The file could not be read");
Console.WriteLine(e.Message);
}
isbns = isbns + "~";
System.IO.Directory.CreateDirectory(@"c:\data\ReadytoReturn");
return new Response() { isbn= isbns };
}
}
}
HTML看起来像这样:
<script type="text/javascript">
$(function() {
$.getJSON( 'http://192.168.64.180/dobits/service.svc/GetCustomer?callback=?', null, function(res){
//console.log(res); // log the result from the callback
//var parsed = jQuery.parseJSON(res);
$.each(res, function(key, val) {
var first = val.indexOf("~");
var next = val.indexOf("~",first+1);
while (next>=0)
{
$("#homeJacket").append('<p>'+val.substring(first+1,next)+'</p>');
first=next;
next=val.indexOf("~",first+1);
}
});
});
});
</script>
<div id="homeJacket">
<p></p>
</div>
我从firebug获得的错误消息是:
SyntaxError: invalid label
{"isbn":"~1234567890~"}
答案 0 :(得分:0)
我能够使用此处描述的技术将其转换为JSONP:
https://sites.google.com/site/dhtmlexperiments/blogs/crossdomainrestfulserviceinwcf