85 lines
3.1 KiB
C#
85 lines
3.1 KiB
C#
using Domain.AggregateModel.AppAggregate;
|
|
using Domain.AggregateModel.LinkAggregate;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using QRCodeService.Models;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using MediatR;
|
|
using QRCodeService.Application.Queries;
|
|
using QRCodeService.Application.Commands;
|
|
using QRCodeService.Infrastructure.Middlewares;
|
|
using QRCodeService.Options;
|
|
using QRCoder;
|
|
using System.Drawing;
|
|
using System.IO;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace QRCodeService.Controllers.Api
|
|
{
|
|
[Route("api/v1/[controller]")]
|
|
[ApiController]
|
|
public class LinkController:ControllerBase
|
|
{
|
|
readonly IMediator mediator;
|
|
readonly ILinkQueries linkQueries;
|
|
readonly IOptions<ServiceOption> option;
|
|
|
|
public LinkController(IMediator mediator, ILinkQueries queries, IOptions<ServiceOption> option)
|
|
{
|
|
this.mediator = mediator;
|
|
this.linkQueries = queries;
|
|
this.option = option;
|
|
}
|
|
[Route("i/{shortCode}/")]
|
|
[HttpGet]
|
|
public async Task<IActionResult> GetQrCodeImage(string shortCode)
|
|
{
|
|
var link = await linkQueries.GetLinkAsync(shortCode);
|
|
if (link == null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
var qrCodeGenerator = new QRCodeGenerator();
|
|
var data = qrCodeGenerator.CreateQrCode($"{option.Value.BaseUrl}r/{link.ShortCode}", QRCodeGenerator.ECCLevel.Q);
|
|
var qrCode = new QRCode(data);
|
|
using (var stream = new MemoryStream())
|
|
{
|
|
qrCode.GetGraphic(10, Color.Black, Color.White, null, 15, 6, false).Save(stream, System.Drawing.Imaging.ImageFormat.Png);
|
|
return File(stream.ToArray(), "image/png");
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// 创建二维码 如果请求头的Accept类型是image/png 则会返回二维码图片 否则返回二维码地址
|
|
/// </summary>
|
|
/// <param name="input"></param>
|
|
/// <returns></returns>
|
|
[CheckSign]
|
|
[HttpPost]
|
|
public async Task<IActionResult> Create(CreateLinkModel input)
|
|
{
|
|
var command = new CreateLinkCommand(input.SuffixUrl,1);
|
|
var link = await mediator.Send(command);
|
|
if (link==null)
|
|
{
|
|
return BadRequest();
|
|
}
|
|
var accept = Request.Headers["Accept"];
|
|
if(accept == "image/png")
|
|
{
|
|
var qrCodeGenerator = new QRCodeGenerator();
|
|
var data = qrCodeGenerator.CreateQrCode($"{option.Value.BaseUrl}r/{link.ShortCode}", QRCodeGenerator.ECCLevel.Q);
|
|
var qrCode = new QRCode(data);
|
|
using (var stream = new MemoryStream())
|
|
{
|
|
qrCode.GetGraphic(10, Color.Black, Color.White, null, 15, 6, false).Save(stream, System.Drawing.Imaging.ImageFormat.Png);
|
|
return File(stream.ToArray(), "image/png");
|
|
}
|
|
}
|
|
return Ok($"{option.Value.BaseUrl}r/{link.ShortCode}");
|
|
}
|
|
}
|
|
}
|