Reputation: 21
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)" />
Upvotes: 1
Views: 9286
Reputation: 247511
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.
Upvotes: 3