Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
signalr / SignalR Programming in Microsoft ASP.NET.pdf
Скачиваний:
65
Добавлен:
25.05.2015
Размер:
19.23 Mб
Скачать

FIGURE 6-3  System for tracing connections in operation.

Project creation and setup

For the purpose of creating the application that we will develop over the following pages, it is necessary to first create a project of the “ASP.NET Web Application” type from Visual Studio 2013 and then select the “Empty” template to create a completely empty project1. The version of the .NET Framework used must be at least 4.5.

After we have created it, we must install the following package using NuGet:

PM> install-package Microsoft.AspNet.SignalR

1 In Visual Studio 2012, we can achieve the same goal by creating a project from the template “ASP.NET Empty Web Application.”

Persistent connections and hubs from other threadsChapter 6

107

www.it-ebooks.info

Implementing the website

Page markup (default.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ConnectionSpy.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">

<title><%: Title %></title>

<script src="Scripts/jquery-1.6.4.min.js"></script> </head>

<body>

<h1><%: Title %></h1>

<form id="form1" runat="server"> <div>

<p>This is the content of the <%: Title %></p> <h3>Navigation links</h3>

<asp:PlaceHolder runat="server" ID="placeHolder"> </asp:PlaceHolder>

</div>

<a href="Spy.html" target="_blank"> Spy requests (new window)

</a>

</form>

</body>

</html>

Code-behind (default.aspx.cs)

using System; using System.Text;

using System.Web.UI; namespace ConnectionSpy

{

public partial class Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

int id;

this.Title = int.TryParse(Request["id"], out id) ? "Page " + id

: "Home page";

var html = new StringBuilder(); html.AppendLine("<ul>");

for (int i = 1; i < 11; i++)

{

var text = "Page " + i; var link = string.Format(

"<li><a href='Default.aspx?id={0}'>{1}</a></li>", i, text

);

108 Chapter 6Persistent connections and hubs from other threads

www.it-ebooks.info

html.AppendFormat(link);

}

html.AppendLine("</ul>");

placeHolder.Controls.Add(

new LiteralControl(html.ToString())

);

}

}

}

System for tracing requests (server side)

Persistent connection (ConnectionSpy.cs)

using Microsoft.AspNet.SignalR

public class ConnectionSpy: PersistentConnection

{

}

Note that the body of the persistent connection is empty. We will not need to take control in it when the SignalR clients connect to it, nor will we need to send messages to clients from here; this will be done from the application global class, as we shall see in the “Application global class (Global.asax.cs)” code.

Startup code (Startup.cs)

using Owin;

public class Startup

{

public void Configuration(IAppBuilder app)

{

app.MapSignalR<ConnectionSpy>("/spy");

}

}

Application global class (Global.asax.cs)

using System; using System.Web;

using Microsoft.AspNet.SignalR;

public class Global : HttpApplication

{

private static IPersistentConnectionContext connSpy = GlobalHost.ConnectionManager.GetConnectionContext<ConnectionSpy>();

protected void Application_BeginRequest(object sender, EventArgs e)

{

var context = ((HttpApplication)sender).Context; var message = string.Format(

Persistent connections and hubs from other threadsChapter 6

109

www.it-ebooks.info

"{0}: Requested '{1}' from IP {2} using {3}", DateTime.Now.ToShortTimeString(), context.Request.Url.ToString(), context.Request.UserHostAddress, context.Request.Browser.Type

);

connSpy.Connection.Broadcast(message);

}

}

We could also have implemented this same process as OWIN middleware, instead of doing it in the application global class. In that case, the module would be the following:

using System;

using System.Threading.Tasks; using Microsoft.AspNet.SignalR; using Microsoft.Owin;

public class SpyMiddleware : OwinMiddleware

{

private static IPersistentConnectionContext connSpy = GlobalHost.ConnectionManager.GetConnectionContext<ConnectionSpy>();

public SpyMiddleware(OwinMiddleware next): base(next) { }

public override Task Invoke(IOwinContext context)

{

var message = string.Format(

"{0}: Requested '{1}' from IP {2} using {3}", DateTime.Now.ToShortTimeString(), context.Request.Uri.ToString(), context.Request.Host, context.Request.Headers["USER-AGENT"]

);

return Next.Invoke(context)

.ContinueWith(c => connSpy.Connection.Broadcast(message));

}

}

And to enter this module in the request processing pipeline, we would have to modify the configuration code:

public class Startup

{

public void Configuration(IAppBuilder app)

{

app.MapSignalR<ConnectionSpy>("/spy");

app.Use<SpyMiddleware>();

}

}

110 Chapter 6Persistent connections and hubs from other threads

www.it-ebooks.info

Соседние файлы в папке signalr