既然你說,你不能使用MvcController或Razor視圖,你可以得到更接近金屬:IHttpHandler
。
所以寫一個開始:
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var response = context.Response;
response.ContentType = "text/javascript";
var message = "This is some super dynamic message. The UTC time now is: " + DateTime.UtcNow.ToLongTimeString();
var js = string.Format("alert({0});", new JavaScriptSerializer().Serialize(message));
response.Write(js);
}
public bool IsReusable
{
get { return true; }
}
}
然後寫一個相應的路由處理:
public class MyHandlerProvider: IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new MyHandler();
}
}
,並在您Application_Start
添加路由:
protected void Application_Start()
{
RouteTable.Routes.Add(
new Route(
"eventAggregation/events",
new MyHandlerProvider()
)
);
}
如果你沒不想手動在您的Application_Start
中添加路線,您可以使用WebActivator
。簡單地寫一個靜態的啓動類:
internal static class Startup
{
public static void Application_Start()
{
RouteTable.Routes.Add(
new Route(
"eventAggregation/events",
new MyHandlerProvider()
)
);
}
}
,然後使用裝配寬屬性:
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MvcApplication1.Startup), "Application_Start")]
而現在,所有剩下的在你看來是引用它:
<script type="text/javascript" src="~/eventAggregation/events"></script>
我我從來沒有使用它,但從我的理解,'Node.js'用於此。 – 2013-05-14 01:15:18
您希望我將後端更改爲Node.js? – Anders 2013-05-15 08:09:45