由于您声明不能使用 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
. 只需编写一个静态 Startup 类:
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>