In this article I will explain with an example, how to switch between front and back camera in Web Camera (Webcam) using jQuery in ASP.Net Core (.Net Core 7) Razor Pages.
Note: For beginners in ASP.Net Core (.Net Core 7) Razor Pages, please refer my article ASP.Net Core 7 Razor Pages: Hello World Tutorial with Sample Program example.
 
The images (photos) captured using Web Camera (Webcam) will be saved in folder and displayed in View in ASP.Net Core (.Net Core 7) Razor Pages.
 
 

jQuery Webcam Plugin

This article uses jQuery Webcam plugin is used to capture images (photos) from Web Camera (Webcam).
For more information, please refer jQuery Webcam Plugin Documentation.
 
 

Razor PageModel (Code-Behind)

The PageModel consists of following Handler methods.

Handler Method for handling GET operation

Inside this Handler method, simply the View is returned.
 

Handler Method for handling POST operation

Inside this Handler method, the Captured Image is received in BASE64 string format.

Attributes

ValidateAntiForgeryToken: The ValidateAntiForgeryToken attribute is used to prevent cross-site request forgery attacks.
Note: A cross-site request forgery is an attack is done by sending harmful script element, malicious command, or code from the user’s browser.
 
Then, the BASE64 string is converted into a BYTE Array and the BYTE Array is saved as Image file in the Folder (Directory).
Finally, an EmptyResult (NULL) is returned.
public class IndexModel : PageModel
{
    private IWebHostEnvironment Environment;
 
    public IndexModel(IWebHostEnvironment _environment)
    {
        this.Environment = _environment;
    }
 
    public void OnGet()
    {
    }
 
    [ValidateAntiForgeryToken]
    public ActionResult OnPostSaveCapturedImage(string data)
    {
        string fileName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
 
        //Convert Base64 Encoded string to Byte Array.
        byte[] imageBytes = Convert.FromBase64String(data.Split(',')[1]);
 
        //Save the Byte Array as Image File.
        string filePath = Path.Combine(this.Environment.WebRootPath, string.Format("Captures/{0}.jpg", fileName));
        System.IO.File.WriteAllBytes(filePath, imageBytes);
        return new EmptyResult();
    }
}
 
 

Razor Page (HTML)

HTML Markup

The View consists of following elements:
div – For displaying Live Web Camera.
Image – For displaying the captured image.
Button – For capturing the picture using the Web Camera and one for uploading in the Folder (Directory).
Inside the View, the following script files are inherited.
1. jquery.min.js
2. webcam.js
 

Capturing the Image from Web Camera (Webcam)

When the Capture Button is clicked, the Image is captured from Web Camera (Webcam) using the snap function of the jQuery Webcam plugin.
Then the captured Image data in BASE64 string format is assigned to the HTML Image element.
 

Switching the facing mode of Web Camera (Webcam)

When Switch Button is clicked, the facingmode of jQuery Webcam plugin is switched.
facingMode has following two options:
environment - To access the rear camera.
user - To access the front camera. It is by default if not set.
 

Uploading the Image from Web Camera (Webcam)

When the Upload Button is clicked, the captured Image data in BASE64 string format is uploaded to Server using jQuery AJAX call and then inside the SaveCapture Action method, it is converted into Image file and saved in Folder (Directory).
 

Applying the jQuery Webcam plugin

Inside the jQuery document ready event handler, the jQuery Webcam plugin is applied to the HTML div.
The following are the configuration properties of the jQuery Webcam plugin:
width – Width of the DIV that displays the live camera.
height – Height of the DIV that displays the live camera.
image_format – The file format of the Image i.e. JPEG, PNG, etc.
jpeg_quality – The quality of the captured Image.
 
The Anti-Forgery Token has been added to Razor Page using the AntiForgeryToken function of the HTML Helper class.
Inside the ButtonClick function, the $http service is used to make an AJAX call to the Handler method.
The $http service has following properties and methods.

Properties

1. method – The method type of HTTP Request i.e. GET or POST.
2. url – URL of the Handler method. In this case /Index?handler=SaveCapturedImage.
Note: In the Razor PageModel, the Handler method name is OnPostSaveCapturedImage but here it will be specified as SaveCapturedImage when calling from the Razor HTML Page.
 
3. datatype – The format of the data i.e. XML or JSON.
4. data – The parameters to be sent to the Handler method.
5. headers – List of headers to be specified for the HTTP Request.
The value of the Anti-Forgery Token is read from the Hidden Field added by the Html.AntiForgeryToken HTML Helper function and added to the headers property of $http service.
Note: Without passing Anti-Forgery Token, the AJAX call to the Handler method of the Razor PageModel will not work.
 
@page
@model Switch_WebCam_jQuery_Core_Razor.Pages.IndexModel
@{
 
}
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @Html.AntiForgeryToken()
    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <th align="center"><u>Live Camera</u></th>
            <th align="center"><u>Captured Picture</u></th>
        </tr>
        <tr>
            <td><div id="webcam"></div></td>
            <td><img id="imgCapture" /></td>
        </tr>
        <tr>
            <td align="center">
                <input type="button" id="btnFrontBack" value="Back" />
                <input type="button" id="btnCapture" value="Capture" />
            </td>
            <td align="center">
                <input type="button" id="btnUpload" value="Upload" disabled="disabled" />
            </td>
        </tr>
    </table>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/webcamjs/1.0.26/webcam.js"></script>
    <script type="text/javascript">
        $(function () {
            ApplyPlugin();
            $("#btnCapture").click(function () {
                Webcam.snap(function (data_uri) {
                    $("#imgCapture")[0].src = data_uri;
                    $("#btnUpload").removeAttr("disabled");
                });
            });
 
            $("#btnFrontBack").click(function () {
                $('#btnFrontBack').val($('#btnFrontBack').val() == 'Back' ? 'Front' : 'Back');
                Webcam.reset();
                ApplyPlugin();
            });
        });
 
        function ApplyPlugin() {
            var mode = $('#btnFrontBack').val() == 'Back' ? 'user' : 'environment';
            Webcam.set({
                width: 320,
                height: 240,
                image_format: 'jpeg',
                jpeg_quality: 90,
                constraints: { facingMode: mode }
            });
            Webcam.attach('#webcam');
        }
 
        $("body").on("click", "#btnUpload", function () {
            var token = $('input:hidden[name="__RequestVerificationToken"]').val();
            $.ajax({
                type: "POST",
                url: "/Index?handler=SaveCapturedImage",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN", token);
                },
                data: { data: $("#imgCapture")[0].src },
                success: function (r) { }
            });
        });
    </script>
</body>
</html>
 
 

Screenshot

ASP.Net Core Razor Pages: Switch between Front and Back camera in WebCam using jQuery
 
 

Browser Compatibility

The above code has been tested in the following browsers only in versions that support HTML5.
Microsoft Edge  FireFox  Chrome  Safari  Opera
* All browser logos displayed above are property of their respective owners.
 
 

Demo

 
 

Downloads



Other available versions