galaeth-draft/Galaeth.ApiServer/Controllers/ApiController.cs

108 lines
3.1 KiB
C#
Raw Normal View History

2024-11-17 10:31:01 +01:00
using System.Net;
using System.Net.Sockets;
using Galaeth.ApiServer.Models.Common;
using Galaeth.Core.Constants;
using Microsoft.AspNetCore.Mvc;
namespace Galaeth.ApiServer.Controllers;
/// <summary>
/// Base Api Controller.
/// </summary>
[Consumes("application/json")]
[Produces("application/json")]
public class ApiController : ControllerBase
{
/// <summary>
/// Return a failure status with no data.
/// </summary>
/// <returns>Instance of <see cref="IActionResult"/>.</returns>
protected static IActionResult FailureResult()
{
return new JsonResult(new ResultModel
{
Success = false,
});
}
/// <summary>
/// Return a failure result with additional information.
/// </summary>
/// <param name="errorCode">Api error code.</param>
/// <param name="message">Api error message.</param>
/// <returns>Instance of <see cref="IActionResult"/>.</returns>
protected static IActionResult FailureResult(string errorCode, string message)
{
return new JsonResult(new ErrorResultModel
{
Error = errorCode,
Message = message,
});
}
/// <summary>
/// Returns a failure result indicating the body is missing from the request.
/// </summary>
/// <returns>Instance of <see cref="IActionResult"/>.</returns>
protected static IActionResult MissingBodyResult()
{
return FailureResult(CoreErrorCodes.NoDataProvided, "Missing request body");
}
/// <summary>
/// Return a success status with no data.
/// </summary>
/// <returns>Instance of <see cref="IActionResult"/>.</returns>
protected static IActionResult SuccessResult()
{
return new JsonResult(new ResultModel
{
Success = true,
});
}
/// <summary>
/// Return a success status with data.
/// </summary>
/// <returns>Instance of <see cref="IActionResult"/>.</returns>
/// <typeparam name="TDataType">The primary key type.</typeparam>
/// <param name="data">The data to return in the result.</param>
protected static IActionResult SuccessResult<TDataType>(TDataType data)
where TDataType : class
{
return new JsonResult(new DataResultModel<TDataType>
{
Data = data,
Success = true,
});
}
/// <summary>
/// Fetch IP address of requesting agent.
/// </summary>
/// <returns>Request origin's IP address.</returns>
protected IPAddress ClientIpAddress()
{
IPAddress remoteIpAddress = null;
if (Request.Headers.TryGetValue("X-Forwarded-For", out var value))
{
foreach (var ip in value)
{
if (IPAddress.TryParse(ip, out var address) &&
(address.AddressFamily is AddressFamily.InterNetwork
or AddressFamily.InterNetworkV6))
{
remoteIpAddress = address;
break;
}
}
}
else
{
remoteIpAddress = HttpContext.Connection.RemoteIpAddress?.MapToIPv4();
}
return remoteIpAddress;
}
}