Skip to content

Instantly share code, notes, and snippets.

@oliveira-michel
Created March 10, 2020 14:23
Show Gist options
  • Save oliveira-michel/b3ff3face96202a7ba44d6825ffec1a2 to your computer and use it in GitHub Desktop.
Save oliveira-michel/b3ff3face96202a7ba44d6825ffec1a2 to your computer and use it in GitHub Desktop.
Exemplo de consulta com Accepts diferentes (binario x json)
[HttpGet("contas/{idConta}/extrato")]
[Produces("application/json", "application/pdf")]
public ActionResult<ExtratoModel> GetExtrato([FromHeader] string accept, [FromQuery] string fromData)
{
string[] acceptedTypes = accept.Split(',')
.Select(type => MediaTypeHeaderValue.Parse(type))
.OrderByDescending(type => type.Parameters.FirstOrDefault(p => p.Name == "q")?.Value)
.Select(type => type.ToString()).ToArray();
foreach (string acceptedType in acceptedTypes)
{
switch (acceptedType)
{
case "application/json":
return new ExtratoModel()
{
Saldo = 12.33,
Lancamentos = new List<ExtratoModel.Lancamento>()
{
new ExtratoModel.Lancamento()
{
Data = DateTime.UtcNow.ToString("O"),
Descricao = "Pagamento",
Valor = 123.45
}
}
};
case "application/pdf":
var pdf = new MemoryStream(); //Seu método que gera o PDF ...
return new FileContentResult(pdf.ToArray(), "application/pdf")
{
FileDownloadName = "extrato.pdf"
};
}
}
//Tratamento de erro ...
Response.StatusCode = 406;
return null;
}
public class ExtratoModel
{
public double Saldo { get; set; }
public List<Lancamento> Lancamentos { get; set; } = new List<Lancamento>();
public class Lancamento
{
public string Data { get; set; }
public string Descricao { get; set; }
public double Valor { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment