我正在编写一个监控公司服务器的应用程序。该应用程序使用asp.net核心Web API。该应用程序维护已知服务器的列表。当get请求进入时,它将以其自己的状态或另一个服务器的状态进行响应。在来自其他服务器的响应的情况下,我想转发响应,https状态代码和所有。其他服务器是内部的,所以我不能只发出HTTP重定向。
这是我现在使用的方法。当我请求另一个服务器名称时,我当前获得了http状态代码500。另一台服务器当前没有运行,所以我期待404状态代码。
public async Task<IActionResult> Get(string name)
{
if (Dns.GetHostName().Equals(name, StringComparison.InvariantCultureIgnoreCase))
{
return await GetThis();
}
var instanceUri = _context.InstanceUri(name);
if (instanceUri == null)
{
return BadRequest(name);
}
var serverUrl = new Uri($"{instanceUri}{Url.Action(nameof(GetThis))}");
var remoteRequest = new HttpClient()
{
BaseAddress = serverUrl
}.GetAsync(serverUrl);
await remoteRequest;
//TODO: Handle errors and forward proper status codes
return new ObjectResult(remoteRequest);
}
这是完整的控制器:
/// <summary>
/// Controller for getting server information.
/// </summary>
[Route("api/[controller]")]
public class ServerController : Controller
{
private readonly ApplicationGlobalContext _context;
public ServerController(ApplicationGlobalContext context)
{
_context = context;
}
/// <summary>
/// Gets a list of server names
/// </summary>
/// <returns></returns>
[HttpGet]
public IEnumerable<string> Get()
{
return _context.InstanceNames;
}
/// <summary>
/// Gets status of this server
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> GetThis()
{
var computerInfo = new ComputerInfo();
var hostName = Dns.GetHostName();
var hostAddresses = Dns.GetHostAddressesAsync(hostName);
return new ObjectResult(new Server()
{
Name = hostName,
IpAddresses = await hostAddresses,
Memory = new Memory()
{
AvailablePhysicalMemory = computerInfo.AvailablePhysicalMemory,
AvailableVirtualMemory = computerInfo.AvailableVirtualMemory,
TotalPhysicalMemory = computerInfo.TotalPhysicalMemory,
TotalVirtualMemory = computerInfo.AvailableVirtualMemory,
},
});
}
/// <summary>
/// Gets a server by name
/// </summary>
/// <param name="name">The name of the server</param>
/// <returns></returns>
[HttpGet("{name}")]
public async Task<IActionResult> Get(string name)
{
if (Dns.GetHostName().Equals(name, StringComparison.InvariantCultureIgnoreCase))
{
return await GetThis();
}
var instanceUri = _context.InstanceUri(name);
if (instanceUri == null)
{
return BadRequest(name);
}
var relUri = Url.Action(nameof(GetThis));
var serverUrl = new Uri($"{instanceUri}{Url.Action(nameof(GetThis))}");
var remoteRequest = new HttpClient()
{
BaseAddress = serverUrl
}.GetAsync(serverUrl);
await remoteRequest;
//TODO: Handle errors and forward proper status codes
return new ObjectResult(remoteRequest);
}
}