如何在ASP.NET MVC中通过HTML文本框设置C#控制器字符串变量
解决方案:点击按钮将输入IP赋值给控制器变量并执行登录
按以下步骤修改代码,即可实现需求:
1. 解决控制器配置持久化问题
ASP.NET Core的控制器是瞬时对象,每次请求都会创建新实例,直接用控制器字段存储machineIP会导致每次请求重置为默认值。需要创建单例服务来保存配置:
创建MachineConfigService.cs服务类:
namespace MachineManager.Services { public class MachineConfigService { public string MachineIP { get; set; } = "192.168.10.107"; public string Url { get; set; } = "https://192.168.10.107/selfcashapi"; } }
在Program.cs注册为单例:
builder.Services.AddSingleton<MachineConfigService>();
2. 修改控制器逻辑,注入配置服务
更新VNEcontroller.cs,替换原有字段为注入的配置服务,确保IP和URL在请求间保持一致:
using MachineManager.Models; using MachineManager.Services; using Microsoft.AspNetCore.Mvc; using System.Net; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace MachineManager.Controllers { [ApiController] [Route("api/[controller]")] public class VNEcontroller : Controller { private readonly MachineConfigService _configService; // 注入配置服务 public VNEcontroller(MachineConfigService configService) { _configService = configService; } [HttpPost("SetIP")] public IActionResult SetIP([FromForm] string VNEIP) { if (!string.IsNullOrEmpty(VNEIP)) { _configService.MachineIP = VNEIP; _configService.Url = $"https://{VNEIP}/selfcashapi/"; } return Ok(new VNEViewModel { machineIP = _configService.MachineIP, url = _configService.Url }); } [HttpPost("Login")] public IActionResult Login() { var httpWebRequest = (HttpWebRequest)WebRequest.Create(_configService.Url); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { object jsonObj = new { tipo = 40 }; string json = JsonConvert.SerializeObject(jsonObj); streamWriter.Write(json); } string result = ""; var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { result = streamReader.ReadToEnd(); } JObject jObject = JObject.Parse(result); string req_status = jObject["req_status"]?.ToString(); return Ok(req_status); } // EmptyHopper方法同样替换为使用配置服务的Url [HttpPost("EmptyHopper")] public IActionResult EmptyHopper(bool totalEmpty = true) { var httpWebRequest = (HttpWebRequest)WebRequest.Create(_configService.Url); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { object jsonObj = new { tipo = 50, full = totalEmpty ? 0 : 1 }; string json = JsonConvert.SerializeObject(jsonObj); streamWriter.Write(json); } string result = ""; var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { result = streamReader.ReadToEnd(); } return Ok(result); } } }
3. 前端视图添加交互逻辑
更新JCash.cshtml,补充JavaScript函数实现“先更新IP再登录”的流程:
@page @using MachineManager.Controllers @model VNEViewModel @{ ViewData["Title"] = "VNE JCash Manager"; } <html> <head> <title>JCash Manager</title> </head> <body> <div> <input id="IPlabel" name="VNEIP" type="text" placeholder="IP da Máquina" /> <button id="callLogin" type="button" onclick="Login()">Conectar</button> </div> <script> async function Login() { const ip = document.getElementById('IPlabel').value.trim(); if (!ip) { alert('Por favor, insira o IP da máquina!'); return; } try { // 第一步:把IP传给后端更新配置 await fetch('/api/VNE/SetIP', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `VNEIP=${encodeURIComponent(ip)}` }); // 第二步:执行登录请求 const response = await fetch('/api/VNE/Login', { method: 'POST', headers: { 'Content-Type': 'application/json', } }); const result = await response.text(); console.log('Resultado do Login:', result); alert('Conectado com sucesso! Resultado: ' + result); } catch (error) { console.error('Erro:', error); alert('Ocorreu um erro ao conectar!'); } } </script> </body> </html>
核心说明
- 单例服务
MachineConfigService负责持久化IP和URL,避免控制器每次请求重置配置。 - 前端通过异步请求分两步操作:先更新IP配置,再执行登录,保证登录时使用最新输入的IP。
- 移除了原表单的跳转逻辑,改用Fetch API实现无刷新交互,更符合现代Web应用的体验。
内容的提问来源于stack exchange,提问作者Guilherme Silvestre
相关产品推荐
相关产品推荐

