简体   繁体   中英

Asynchronous Fetch method call - object reference not set to an instance of an object

im trying to setup the Fetch API which should call a method on the server side.

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");
});

Server class

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
}

The javascript method call the OnGetStartServer method and throw this error: "Object reference not set to an instance of an object"

All objects are null - how I can solve it without reinitializeit?

Regards Timo

The page model is instantiated and disposed with each request. Therefore anything set on a property, field, etc. goes away at the end of the request. Whatever code initializes the member must be run for each handler that needs to use it, plain and simple.

If you need to persist something like the serverId that was used to create it previously, then you can use Session for that, and then pull it from Session on the next request to re-initialize your Server member. For example:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM