1

I'm using ASP.NET identity 2 and one of the tutorials includes using a 3rd part provider to generate a QR Code for Google authenticator for two-factor authentication. However, I don't want to send that data to a 3rd party (which is what other solutions point to, like google, etc). I'm specifically looking for code to solve my issue.

I'd like either the server or the client to generate the QR Code. Anyone else have a good solution for doing this? Below is the line of code that generates the QR Code in the cshtml file. The @(Model.BarcodeURL) is the razor model attribute with the data for the QR Code.

        <img src="http://qrcode.kaywa.com/img.php?s=4&d=@(Model.BarcodeUrl)" />
Spacepirate
  • 21
  • 2
  • 4
  • 1
    Possible duplicate of [Free c# QR-Code generator](http://stackoverflow.com/questions/7020136/free-c-sharp-qr-code-generator) – Peter O. Dec 06 '15 at 15:33
  • Not a duplicate, I'm looking for a solution that will work as part of an MVC project with razor pages in cshtml. The other question/solution is much more generic and one of the solutions says to use a 3rd party (google), which I want to avoid. – Spacepirate Dec 09 '15 at 05:23
  • We can do it by using C# code but for that we need to write very much code if you needed that i can provide you. – Vaibhav Chaurasiya Dec 09 '15 at 12:06

1 Answers1

3

I was able to do this on the server using ZXing.Net and exposing an endpoint via a controller(MVC or Web API). The endpoint would receive data via query string and generate a QRCode on the server using ZXing.Net, then send it back as a stream. This allows one to show the code as an image.

<img src="http://localhost/barcode?d=@(Model.BarcodeUrl)" />

A MVC controller for the above src could look something like this.

....
using ZXing;
using ZXing.QrCode;
using ZXing.QrCode.Internal;
using System.Windows.Media.Imaging // for SaveJpeg extension
....
public class BarcodeController : Controller {
    readonly IBarcodeWriter qrCodeWriter;

    BarcodeController() {
        qrCodeWriter = new BarcodeWriter {
            Format = BarcodeFormat.QR_CODE,
            Options = new QrCodeEncodingOptions {
                Margin = 1,
                Height = 600,
                Width = 600,
                ErrorCorrection = ErrorCorrectionLevel.Q,
            },
        };
    }

    public ActionResult Index(string d) {
        var writeableBitmap = qrCodeWriter.Write(d);
        var memoryStream = new MemoryStream();
        writeableBitmap.SaveJpeg(memoryStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);
        return File(memoryStream.GetBuffer(), "image/jpeg");
    }
}

Should be easy enough to do the same thing via an ApiController. You could also refactor out the code generation into a dedicated class if you want to separate concerns.

Nkosi
  • 235,767
  • 35
  • 427
  • 472