2
我正在構建JSONP服務。錯誤格式的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>
的錯誤信息,我從螢火蟲得到的是:
SyntaxError: invalid label
{"isbn":"~1234567890~"}