کار با SignalR Core از طریق یک کلاینت Angular
نویسنده: وحید نصیری
تاریخ: ۱۳۹۶/۰۶/۲۷ ۱۳:۴۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
dotnet new mvc
ng new SignalRCore2Client
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.0.0-alpha1-final" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" />
</ItemGroup>
</Project> dotnet restore
dotnet watch run
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
namespace SignalRCore2WebApp.Hubs
{
public class MessageHub : Hub
{
public Task Send(string message)
{
return Clients.All.InvokeAsync("Send", message);
}
}
} public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
services.AddMvc();
} public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSignalR(routes =>
{
routes.MapHub<MessageHub>(path: "message");
}); http://localhost:5000/message
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using SignalRCore2WebApp.Hubs;
namespace SignalRCore2WebApp.Controllers
{
public class HomeController : Controller
{
private readonly IHubContext<MessageHub> _messageHubContext;
public HomeController(IHubContext<MessageHub> messageHubContext)
{
_messageHubContext = messageHubContext;
}
public IActionResult Index()
{
return View(); // show the view
}
[HttpPost]
public async Task<IActionResult> Index(string message)
{
await _messageHubContext.Clients.All.InvokeAsync("Send", message);
return View();
}
}
} @{
ViewData["Title"] = "Home Page";
}
<form method="post"
asp-action="Index"
asp-controller="Home"
role="form">
<div class="form-group">
<label label-for="message">Message: </label>
<input id="message" name="message" class="form-control"/>
</div>
<button class="btn btn-primary" type="submit">Send</button>
</form> npm install @aspnet/signalr-client --save
import { Component, OnInit } from "@angular/core";
import { HubConnection } from "@aspnet/signalr-client";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
hubPath = "http://localhost:5000/message";
messages: string[] = [];
ngOnInit(): void {
const connection = new HubConnection(this.hubPath);
connection.on("send", data => {
this.messages.push(data);
});
connection.start().then(() => {
// connection.invoke("send", "Hello");
console.log("connected.");
});
}
} <div>
<h1>
The messages from the server:
</h1>
<ul>
<li *ngFor="let message of messages">
{{message}}
</li>
</ul>
</div> ng serve -o
Failed to load http://localhost:5000/message: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddMvc();
} public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(policyName: "CorsPolicy");
import { HubConnection } from "@aspnet/signalr-client"; import { HubConnection } from "@aspnet/signalr"; this.Clients.Client(this.Context.ConnectionId).SendAsync("method", "message")
با این شرایط البته:
- سرویس مدنظر پیشتر در فایل آغازین برنامه ثبت شده باشد:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IMyService, MyService>();
} public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSignalR(routes =>
{
routes.MapHub<MessageHub>(path: "/message");
}); <PackageReference Include = "Microsoft.AspNetCore.All" Version = "2.0.0" />
Microsoft.AspNetCore.SignalR <PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.0.0-alpha1-final" />
.SetIsOriginAllowed((host) => true)
npm install @aspnet/signalr --save
let hubConnection = new HubConnectionBuilder()
.withUrl(this.hubPath)
.build(); public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.WithOrigins("http://localhost:4200") //Note: The URL must be specified without a trailing slash (/).
.AllowAnyMethod()
.AllowAnyHeader()
//.SetIsOriginAllowed((host) => true)
.AllowCredentials());
}); WebSocket connection to '(ws://your_domanin_name/message/id=number)' failed: Error during WebSocket handshake:Unexpected response code: 503 Error: Failed to start the transport 'WebSockets': undefined
// Old code:
app.UseSignalR(routes =>
{
routes.MapHub<SomeHub>("/path");
});
// New code:
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<SomeHub>("/path");
}); npm install @microsoft/signalr --save
public Task Send(string message)
{
return Clients.All.InvokeAsync("Send", message);
}