我能够让 Service Stack 的 Hello World 示例正常工作,但现在我正在尝试稍微扩展它以返回自定义Site对象。我制作了一个简单的测试 html 文件,该文件使用 jQuery 来拉回结果,但我没有返回Site对象(我认为)。
这是我的网络服务:
using Funq;
using ServiceStack.ServiceInterface;
using ServiceStack.WebHost.Endpoints;
using System;
namespace My.WebService
{
public class SiteRepository
{
}
public class Site
{
public string Name { get; set; }
public string Uri { get; set; } //switch to the real uri class if you find it useful
}
public class SiteService : Service //: RestServiceBase<Site>
{
public SiteRepository Repository { get; set; } //Injected by IOC
public object Get(Site request)
{
//return new Site { Name = "Google", Uri = "http://www.google.com" };
return new SiteResponse {Result = new Site {Name = "Google", Uri = "http://www.google.com"}};
}
}
public class SiteResponse
{
public Site Result { get; set; }
}
public class SiteAppHost : AppHostBase
{
public SiteAppHost()
: base("Site Web Services", typeof(SiteService).Assembly)
{
}
public override void Configure(Container container)
{
container.Register(new SiteRepository());
Routes
.Add<Site>("/site")
.Add<Site>("/site/{Id}/");
}
}
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
new SiteAppHost().Init();
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
}
这是使用 jQuery 的测试 HTML 文件。我添加了 ?callback=? 因为我正在同时运行 Web 服务和从同一台机器进行调用。
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// we will add our javascript code here
$(document).ready(function() {
// do stuff when DOM is ready
alert("Hello world!");
//the ?callback=? part is for testing on the same server as the web service
$.getJSON("http://localhost:61549/site?callback=?", function(sitesReturned) {
alert(sitesReturned); // alert box contains: [object Object]
alert(sitesReturned.Name); //alert box contains: undefined
alert(sitesReturned.length == 1) //alert box contains: false
var parsed = JSON.parse(sitesReturned); //this fails silently
alert(parsed.Name); // the alert box does not load
});
alert("Goodbye world!");
});
</script>
</head>
<body>
<!-- we will add our HTML content here -->
Hello
</body>
</html>