DEV Community

loading...

Video call with WebRTC Angular and ASP.NET Core

Sebastian Larrieu on January 27, 2020

Hi everyone, in this post we will build a basic video call web using WebRTC,Angular and ASP.Net Core. Why? because this technologies are like read ...
pic
Editor guide
Collapse
vipul83 profile image
vipul83

Hi.. Its a great post...

I m getting "currentpeer" (from rtc.service.ts ) object as undefined when i click on "send" button. so far my camera is activated but no video and chats are coming. any suggestion what i am missing? PFA also

Collapse
sebalr profile image
Sebastian Larrieu Author

You have to click a username to establish s connection before sending data

Collapse
vipul83 profile image
vipul83

Hello Sebastian,

I clicked on user from userlist shown , currentpeer object is initialized though, but still video is not activated, PFA. I found that "connected" property of currentpeer object is set to "false". please suggest wat i m missing.

Thread Thread
vipul83 profile image
vipul83

I am getting attached exception when click on send message. Please note i m the only user who is running this application on my local machine. or does it required more than 1 user to setup communication (video communication)

Thread Thread
sebalr profile image
Sebastian Larrieu Author

You need two users. You can open two browser windows

Thread Thread
vipul83 profile image
vipul83

yup..it works for me when running via vs debug mode on two separate browsers but when i hosted the application on IIS, getting "simplepeer is not defined" error on console.....do I need to configure on IIS ??
also "SendSignal" hub method call is not going thru when hosted on IIS, if i select user

Thread Thread
sebalr profile image
Sebastian Larrieu Author

Sorry, I didn't understand. Why do you need IIS? I use dot net CLI to run the backend and Angular CLI to run frontend (or build and use a server like Apache or nginx) and open two browser to connect to Angular

Thread Thread
vipul83 profile image
vipul83

I need IIS to host. I have to host my web api (signalr svc) and frontend on IIS

Thread Thread
sebalr profile image
Sebastian Larrieu Author

So if you open two browser and use two different user everything must work

Thread Thread
vipul83 profile image
vipul83

No, its not working when hosted on IIS. I am wondering if i need to update anything on IIS related to support simplepeer. Anything you suggest ?

Collapse
saravanakumar491993 profile image
saravanakumar491993

Dear Sebastian,

I'm able to connect with other user using singalr and hello is working. When I choose an user the following error occurs in Angular. Please help me with this.

ReferenceError: SimplePeer is not defined

Collapse
timsar2 profile image
timsar2

import inside styles[] into angular.json file.

Collapse
sebalr profile image
Sebastian Larrieu Author

Maybe you are not importing the library

Collapse
saravanakumar491993 profile image
saravanakumar491993

I did it in angular

npm install simple-peer
npm install @types/simple-peer

It only worked after i add the below script in index.html :(

<script src="https://cdnjs.cloudflare.com/ajax/libs/simple-peer/6.2.1/simplepeer.min.js"></script>

Why is that so. Please help.

Thread Thread
sebalr profile image
Sebastian Larrieu Author

You have to import simple peer in component ts. Check the GitHub

Thread Thread
Collapse
babakmou profile image
Babak

Hi,

Thanks for this post which helped me a lot in understanding webrtc. Could you please help me to solve below issue?
I also downgraded the version of Typescript from 4 to 3.5.3. , same as yours which didn't work.

Error: src/app/rtc.service.ts:31:5 - error TS2322: Type 'BehaviorSubject' is not assignable to type 'BehaviorSubject'.
Types of property 'observers' are incompatible.
Type 'Observer[]' is not assignable to type 'Observer[]'.
Type 'Observer' is not assignable to type 'Observer'.
Type 'UserInfo[]' is not assignable to type 'never[]'.

31     this.users = new BehaviorSubject([]);
Enter fullscreen mode Exit fullscreen mode
Collapse
sebalr profile image
Sebastian Larrieu Author

Is hard to tell without looking your code. You may have two differents versions of rxjs installed or you are importing behaviourSubject from the wrong place.
Or maybe something changes on RTC library and is returning something different

Collapse
babakmou profile image
Babak

It is exactly your code. I have made no changes,
There were some other errors which could be fixed. For example, I had to add type "any" for "data" as parameter of all peer.on() event listeners.

Thread Thread
sebalr profile image
Sebastian Larrieu Author

It may be related to some TS or Angular upgrade. Try changing the empty array param in line 31 to a new types empty array.
Instead of [] change to new Array with UserInfo as type between <<>>

Collapse
landry_80 profile image
lan-dry

Hi. Please I am getting this error:
Access to XMLHttpRequest at 'localhost:5001/signalrtc/negotiate' from origin 'localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

can you help me please??

Collapse
sebalr profile image
Sebastian Larrieu Author

Hi. As the error show, you have to allow origin localhost:4200 to CORS.

Collapse
landry_80 profile image
lan-dry

But the fact is that I did it exactly as you did. But it stills showing that error. this is the startup file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using signalRtc.hubs;

namespace signalRtc
{
public class Startup
{
readonly string MyAllowSpecificOrigins = "AllowOrigins";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(MyAllowSpecificOrigins,
                builder => builder.WithOrigins("http://localhost:4200", "https://localhost:4200")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

        services.AddSignalR();
    }        

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();
        app.UseCors(MyAllowSpecificOrigins);
        // app.UseMvc();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<SignalRtcHub>("/signalrtc");
        });

        app.Run(async(context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

}

Collapse
sebalr profile image
Sebastian Larrieu Author

Hi. As the error shows, you have to allow origin localhost:4200 to CORS. Pleas read the tutorial carefully

Collapse
steveblue profile image
Steve Belovarich

Very cool 😎!

A couple years ago I made something similar that encapsulates all the logic in a service. Could be made to handle AV pretty easily.

github.com/steveblue/ngfx/blob/mas...

Collapse
sebalr profile image
Sebastian Larrieu Author

Very nice, I will look in detail to get some ideas :)

Collapse
timsar2 profile image
timsar2

i used your repo to implement this with ionic.
everything is ok. two client can swap their sdp but onStream wil fire and has data but video element not showing any thing. also browser has permission for mic and camera

Collapse
sebalr profile image
Sebastian Larrieu Author

I have no experience with ionic. Are you seeing any console error?.

Maybe you need to access camera with some plugin

Collapse
timsar2 profile image
timsar2

no errors. with a breakpoint (debugger) onstream has data and will be pass to html video element
but nothing happened ;(

Thread Thread
sebalr profile image
Sebastian Larrieu Author

Sorry I can't help. As I told you I've never use Ionic. I only used cordova and did not have any problem with video tag.

Collapse
avshaheen profile image
Shaheen.Av

Hi..it was a good sample.

I m getting "SimplePeer is not defined" error when i click the user in both browser window. Can any one suggest me what is the problem in it. I implemented exactly like this. This was the error i am getting on it.

Please give me a solution ASP...

Collapse
auxmahesh profile image
aux-mahesh

hi,
i want to Video call integrate in asp.net c# core so how to please guid me

Collapse
sebalr profile image
Sebastian Larrieu Author

Hi, What did you do?
Where are you having problems?
I can help you if you have a particular problem but I'm not a tutor

Collapse
auxmahesh profile image
aux-mahesh

my asp.net core project new Implement of Video call Option so how to do, can you help me ?

Thread Thread
sebalr profile image
Sebastian Larrieu Author

Well, this tutorial show how to integrate video call in Angular using Net Core as signaling service so that's how you do it, if you are not using Angular you could still use the rest of the code as signalR and rtc are pure js libraries.
I'm definitely not going to do your work but if you have a specific questions I will be happy to help.

Thread Thread
auxmahesh profile image
aux-mahesh

Yes, But Video call option without Angular can be Integrate in asp.net core ? if yes, then how to do and all steps give me by code for Add Video call option in Project.

Thread Thread
sebalr profile image
Sebastian Larrieu Author

As I mentioned, signalR and simple-peer are js libraries and web-rtc is available in every modern web browser so yes, you could use them in any fronted technology

Collapse
joemyjlo profile image
Joemy Joseph

Hi, I would like to implement this in . Netcore without angular... just C# on the server-side, and javascript and HTML on the client-side. I already have a fully implemented chatting system, both private and group conversations using WebSockets. I want to learn how to integrate video and audio calls.

Collapse
sebalr profile image
Sebastian Larrieu Author

Hi, both frontend libraries (simple-peer and signalR) are pure js. You could use them in your project. I don't know how to integrate them in one project because I've never used . Net for something else than rest APIs. However you could check the .Net docs on how to integrate signalR, I know it exists and is very simple to follow

Collapse
rudyhadoux profile image
rudyhadoux

Thanks for sharing.

Collapse
timsar2 profile image
timsar2

How to add stun server url?
I added google stun server to simple-peer and it's not working on diffrent network.
But when i used peerjs with stun server it worked

Collapse
sebalr profile image
Sebastian Larrieu Author

Hello, how are you? I'm fine, thanks for asking. This is a nice community, no stack overflow, so please be nice.
Your questions make no sense, this to tutorial is about implementing your own signaling server, if you need something different you should read simple peer documentation

Collapse
timsar2 profile image
timsar2

very nice man :D, i'm fine too :D
yes this is for signaling.
i read simple-peer documentation, but i could't run it. it has error on connection

Collapse
erossini profile image
Enrico Rossini

HI! Do you have a repo for this code? Thank you!

Collapse
sebalr profile image
Sebastian Larrieu Author

Yes, sorry, I forget to put the links in the post. Already updated!

Collapse
enewmen profile image
enewmen

Nice work, I totally appreciate!
But please create a project for the Front-end Angular client in GitHub. I think this will make things a lot easier. The back-end already has a Visual Studio .csproj project.
Please also add some steps to installing the back-end server. The code is explained well enough.
thanks.

Thread Thread
sebalr profile image
Sebastian Larrieu Author

Hi, I use Vs Code so the frontend is a Angular CLI project.
You could run backend with dotnet CLI. As for a proper production setup, it's another tutoría and I'm not an expert

Collapse
avshaheen profile image
Shaheen.Av

SimplePeer is not defined error and Cannot read property 'send' of undefined this error too.
i opened 2 browser and got 2 username also.video was not showing..please help me.

Collapse
avshaheen profile image
Shaheen.Av

hi...i got this error when i implemented exactly like the github repo.

Collapse
teahva profile image
teahva

hey,
cd src/app
ng g service signalr
after this the src/app/signalr.service.spec.ts , src/app/signalr.service.ts
are created but where i can find this files not able to find it

Collapse
krristannn77 profile image
kristan rae arcino

why no screenshots?

Collapse
kirangabhane profile image
kirangabhane

Hi Sebastian, Very nice project. I need the video call in my existing ASP.NET web application. Could you please share the front-end sample on ASP.NET? I appreciate your help.

Collapse
sebalr profile image
Sebastian Larrieu Author

Hi. The frontend project is in Angular, I believe you could embedded it in ASP.NET but I can't help you because I've never use it

Collapse
hctru68 profile image
Huỳnh Công Trứ

Hi Sebastian,
This post is great.
I run it local is good but it's not working when I deployed it online. Front end and back end is deployed on the Ms azure.
Do you know why this issue happends?

Collapse
sebalr profile image
Sebastian Larrieu Author

Hello, I'm not an expert in networking but there could be two problems
One possibility (and easy to fix) it's that your Apache or nginx it's not correctly configured to allow web socket connection. If that is the case, you will see a signalR error in browser console.
If that is not the case and signalR is working ok, it's a webRTC problem, maybe some users are behind NAT or firewall, in that case you need to host and configure (config in peer constructor) a TURN server.

Edit. Another problem could be that outside localhost you need Https o video and audio request in browser it's not going to work

Collapse
gerwald profile image
Gerwald

Nice work - thanks!
Does the code also work, when the user is behind a firewall/NAT?

Collapse
sebalr profile image
Sebastian Larrieu Author

Thanks for reading!
Behind a firewall or NAT the connection may not work, I'm not an expert in networks so I can't tell you exactly when and why, we make some test with friends behind a NAT and it work.
If it's not the case, and if you coluld not open ports, you need a TURN server, there are open source alternatives that you could host. When the server is running, you have to set it in the config section of the peer constructor.

Collapse
satyamsoni1990 profile image
satyam soni

i am not able to run .net application and getting below mention error
crit: Microsoft.AspNetCore.Server.Kestrel[0]
Unable to start Kestrel.
Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: The system cannot find the file specified.
at Internal.Cryptography.Pal.CertificatePal.FromBlobOrFile(Byte[] rawData, String fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(String fileName, String password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName, String password)
at Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader.LoadCertificate(CertificateConfig certInfo, String endpointName)
at Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader.LoadDefaultCert(ConfigurationReader configReader)
at Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader.Load()
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.ValidateOptions()
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.StartAsyncTContext
Unhandled exception. Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: The system cannot find the file specified.
at Internal.Cryptography.Pal.CertificatePal.FromBlobOrFile(Byte[] rawData, String fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(String fileName, String password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName, String password)
at Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader.LoadCertificate(CertificateConfig certInfo, String endpointName)
at Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader.LoadDefaultCert(ConfigurationReader configReader)
at Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader.Load()
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.ValidateOptions()
at Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer.StartAsyncTContext
at Microsoft.AspNetCore.Hosting.WebHost.StartAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String startupMessage)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token, String startupMessage)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.RunAsync(IWebHost host, CancellationToken token)
at Microsoft.AspNetCore.Hosting.WebHostExtensions.Run(IWebHost host)
at signalRtc.Program.Main(String[] args) in G:\TestProject\NewLocha\signalrtc-backend-master\Program.cs:line 17

Collapse
sebalr profile image
Sebastian Larrieu Author

Did you try to Google the error?

Collapse
satyamsoni1990 profile image
satyam soni

yes but not getting any solution

Thread Thread
sebalr profile image
Sebastian Larrieu Author

You have to generate a certificate in the path

Thread Thread
satyamsoni1990 profile image
satyam soni

no, but now i am facing another issue (Can't join room, error Error) that issue was fixed when create project using visual studio and run by visual studio .
thanks for your time

Thread Thread
sebalr profile image
Sebastian Larrieu Author

You have to use two browser with two different user. One for start the conversation and another to join

Some comments have been hidden by the post's author - find out more