Files
OnDoc/API_NetFramework/Controllers/JsonController.cs
Stefan Hutter 30d047e33d update 20260220
2026-02-20 18:04:31 +01:00

317 lines
11 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using SecuringWebApiUsingApiKey.Middleware;
using System.Threading.Tasks;
using Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web.Http.Results;
using System.Net.Http.Headers;
using System.Drawing;
using Syncfusion.DocIO.DLS;
namespace OnDocAPI_NetFramework.Controllers
{
public class JsonRequestDto
{
public string Key { get; set; }
public string Json { get; set; }
}
[System.Web.Http.RoutePrefix("api/json")]
public class JsonController : ApiController
{
private readonly string _connectionString = StringCipher.Decrypt(ConfigurationManager.ConnectionStrings["DocTesterconnectionstring"].ConnectionString, "i%!k!7pab%bNLdA5hE4pkR4XaB%E^jB3d9tHuQ4pbF&BZjF7SB#WBWit5#HrbJiLrLVm");
// 🔹 JSON LESEN
[System.Web.Http.HttpGet]
[System.Web.Http.Route("load/{key}")]
public IHttpActionResult LoadJson(string key)
{
if (string.IsNullOrWhiteSpace(key))
return BadRequest("Key fehlt");
string json;
using (SqlConnection con = new SqlConnection(_connectionString))
using (SqlCommand cmd = new SqlCommand(
"SELECT JavaScriptObject FROM ProvDokuments WHERE ProvDokumentid = @key", con))
{
cmd.Parameters.AddWithValue("@key", key);
con.Open();
json = cmd.ExecuteScalar()?.ToString();
}
if (json == null)
{
using (SqlConnection con = new SqlConnection(_connectionString))
using (SqlCommand cmd = new SqlCommand(
"SELECT JsonObjekt FROM _OnDoc_API_TestScripts WHERE id = @key", con))
{
cmd.Parameters.AddWithValue("@key", key);
con.Open();
json = cmd.ExecuteScalar()?.ToString();
}
if (json == null) return NotFound();
}
return Ok(json);
}
// 🔹 JSON SPEICHERN
[System.Web.Http.HttpPost]
[System.Web.Http.Route("save")]
public IHttpActionResult SaveJson(JsonRequestDto dto)
{
if (dto == null || string.IsNullOrWhiteSpace(dto.Key))
return BadRequest("Key fehlt");
using (SqlConnection con = new SqlConnection(_connectionString))
using (SqlCommand cmd = new SqlCommand(@"
IF EXISTS (SELECT 1 FROM _OnDoc_API_TestScripts WHERE id = @key)
UPDATE _OnDoc_API_TestScripts SET JsonObjekt =@json
WHERE id = @key
ELSE
INSERT INTO _OnDoc_API_TestScripts (id,JsonObjekt)
VALUES (@key, @json)
", con))
//IF EXISTS (SELECT 1 FROM provdokuments WHERE provdokumentid = @key)
// UPDATE provdokuments SET JavaScriptObject = @json, geaendertam = GETDATE()
// WHERE provdokumentid = @key
//ELSE
// INSERT INTO provdokuments (provdokumentid,erstelltam,geaendertam, JavaScriptObject)
// VALUES (@key, getdate(),getdate(),@json)
//", con))
{
cmd.Parameters.AddWithValue("@key", dto.Key);
cmd.Parameters.AddWithValue("@json", dto.Json);
con.Open();
cmd.ExecuteNonQuery();
}
return Ok();
}
public class JsonRequestDto
{
public string Key { get; set; }
public string Json { get; set; } // ← reiner JSON-String
}
public class PdfBase64Response
{
public string PdfBase64 { get; set; }
}
// 🔹 PDF GENERIEREN
[System.Web.Http.HttpPost]
[System.Web.Http.Route("GeneratePDF")]
public HttpResponseMessage GeneratePdf(JsonRequestDto dto)
{
if (dto == null || string.IsNullOrWhiteSpace(dto.Json))
return new HttpResponseMessage(HttpStatusCode.BadRequest);
byte[] pdfBytes = CallExternalPdfApi(dto.Json);
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(pdfBytes)
};
response.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/pdf");
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("inline")
{
FileName = $"{dto.Key}.pdf"
};
response.Content.Headers.ContentLength = pdfBytes.Length;
return response;
}
private byte[] CallExternalPdfApi(string json)
{
string ownHost = System.Configuration.ConfigurationManager.AppSettings["OwnHost"];
string token = System.Configuration.ConfigurationManager.AppSettings["OwnToken"];
string URL = ownHost + "API/DokumentGenerator";
try
{
var webRequest = System.Net.WebRequest.Create(URL);
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
webRequest.Headers["Authorization"] = "Bearer " + token;
using (System.IO.Stream s = webRequest.GetRequestStream())
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s))
sw.Write(json);
}
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
//System.IO.File.WriteAllText(@"x:\log.txt", ex.ToString());
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
string uri = ownHost + "/API/CreateCLM";
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(uri, content).Result;
string responseContent = response.Content.ReadAsStringAsync().Result;
try
{
// Erfolgsfall
var apiok = JsonConvert.DeserializeObject<APIOK>(responseContent);
if (!string.IsNullOrEmpty(apiok?.file))
{
return Convert.FromBase64String(apiok.file);
}
}
catch
{
// Fehlerfall
var apireturn = JsonConvert.DeserializeObject<APIErrorSimple>(responseContent);
}
}
}
catch (Exception ex)
{
Logging.APIDocLog.Error("API-Call fehlgeschlagen", ex.Message,"","");
}
return null;
//try
//{
// APIErrorSimple apireturn = new APIErrorSimple();
// APIOK apiok = new APIOK();
// ;
// string jsonstring = json;
// WebRequest request;
// var data = Encoding.UTF8.GetBytes(jsonstring);
// string OwnHost = System.Configuration.ConfigurationManager.AppSettings["OwnHost"].ToString();
// string uri = OwnHost + "/API/CreateCLM";
// uri = OwnHost + "/API/DokumentGenerator";
// Logging.APIDocLog.Info("URI", "IIS", "123", uri);
// request = WebRequest.Create(uri);
// request.ContentLength = data.Length;
// request.ContentType = "application/json";
// request.Method = "POST";
// request.Headers["Authorization"] = "Bearer " + System.Configuration.ConfigurationManager.AppSettings["OwnToken"].ToString();
// try
// {
// using (Stream requestStream = request.GetRequestStream())
// {
// requestStream.Write(data, 0, data.Length);
// requestStream.Close();
// using (Stream responseStream = request.GetResponse().GetResponseStream())
// {
// using (var reader = new StreamReader(responseStream))
// {
// var response = reader.ReadToEnd();
// try
// {
// apiok = JsonConvert.DeserializeObject<APIOK>(response);
// var jo = JObject.Parse(response.ToString());
// return Convert.FromBase64String(apiok.file);
// }
// catch (Exception ex)
// {
// apireturn = JsonConvert.DeserializeObject<APIErrorSimple>(response);
// }
// }
// }
// }
// return null;
// }
// catch (Exception ex)
// {
// return null;
// }
//}
//catch {
// byte[] pdf;
// return null;}
//// var request = (HttpWebRequest)WebRequest.Create("https://api.example.com/generate-pdf");
////request.Method = "POST";
////request.ContentType = "application/json";
////byte[] payload = Encoding.UTF8.GetBytes(json);
////request.ContentLength = payload.Length;
////using (var stream = request.GetRequestStream())
//// stream.Write(payload, 0, payload.Length);
////using (var response = (HttpWebResponse)request.GetResponse())
////using (var rs = response.GetResponseStream())
////using (var ms = new MemoryStream())
////{
//// rs.CopyTo(ms);
//// return ms.ToArray();
////}
}
}
}