异步Fetch方法调用-对象引用未设置为对象的实例

时间:2019-06-14 17:06:23

标签: c# asp.net-core razor .net-core fetch-api

im试图设置Fetch API,该API应该在服务器端调用方法。

JavaScript

fetch("/Admin/Server/ac0a45b9-3183-45c9-b4fc-65e37679f1110?handler=StartServer", {
  method: "get",
  headers: {"Content-Type": "application/json"},
  credentials: 'include'
}).then(response => {
  if (!response.ok) {
    throw response;
  }
  return response.json();
}).then(() => {
  console.log("Done");
});

服务器类

private readonly ServerManager ServerManager;

[BindProperty]
public Data.Server.Server Server { get; set; }

public ServerViewModel(ServerContext context, UserContext userContext) {
  this.ServerManager = new ServerManager(context, userContext);
}

public async Task<IActionResult> OnGetAsync(string serverId) {
  if (string.IsNullOrEmpty(serverId)) {
    return NotFound();
  }
  this.Server = await ServerManager.GetServerAsync(serverId);
  return Page();
}

public async Task<JsonResult> OnGetStartServer() {
  // all objects here are null
  return await this.ServerManager.StartServer(this.Server.serverId); // throw npe
}

javascript方法调用OnGetStartServer方法并引发以下错误:“对象引用未设置为对象的实例”

所有对象都为空-如何解决而无需重新初始化?

问候 蒂莫

1 个答案:

答案 0 :(得分:0)

实例化页面模型并随每个请求进行处理。因此,在属性,字段等上设置的所有内容在请求结束时都会消失。无论是什么代码初始化成员,都必须为每个需要使用它的处理程序(无论是简单还是简单)运行。

如果您需要保留先前用于创建它的类似serverId之类的东西,则可以使用Session,然后在下一个请求时将其从Session中提取出来。重新初始化您的Server成员。例如:

public async Task<IActionResult> OnGetAsync(string serverId) {
  if (string.IsNullOrEmpty(serverId)) {
    return NotFound();
  }

  HttpContext.Session.SetString(ServerIdKey, serverId);
  return Page();
}

public async Task<JsonResult> OnGetStartServer() {
  var serverId = HttpContext.Session.GetString(ServerIdKey);
  if (serverId == null)
  {
      // Do something, like redirect to a page where the serverId can be set by the user or whatever
  }    

  return await this.ServerManager.StartServer(serverId);
}
相关问题