webdlh-net/Controllers/ApiProxyController.cs

62 lines
1.9 KiB
C#

using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text;
[ApiController]
[Route("api/[controller]")]
public class ApiProxyController : ControllerBase
{
private readonly HttpClient _httpClient;
private const string N8nWebhookUrl = "http://10.50.50.61:5678/webhook/f2129606-7716-415b-a83b-b9c0e84b752f/chat";
public ApiProxyController(IHttpClientFactory httpClientFactory)
{
_httpClient = httpClientFactory.CreateClient();
}
[HttpPost("chatbot")]
public async Task<IActionResult> Chatbot([FromBody] ChatRequest request)
{
try
{
var payload = new { message = request.Message };
var json = JsonSerializer.Serialize(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(N8nWebhookUrl, content);
if (!response.IsSuccessStatusCode)
{
return StatusCode((int)response.StatusCode, new { code = (int)response.StatusCode, message = "Webhook error: " + await response.Content.ReadAsStringAsync() });
}
var result = await response.Content.ReadAsStringAsync();
try
{
// Try to parse response as JSON
var parsed = JsonSerializer.Deserialize<Dictionary<string, string>>(result);
return Ok(parsed);
}
catch
{
// If not JSON, return as plain text
return Ok(new { reply = result });
}
}
catch (Exception ex)
{
return StatusCode(500, new { message = "Internal server error", error = ex.Message });
}
}
public class ChatRequest
{
public string Message { get; set; } = string.Empty;
}
}