2

I'm working on POSTing data by using UnityWebRequests. Unfortunately this isn't working, although I do not receive any errors.

I've made an API with ASP.NET Core which is working (tested with Postman). I tried multiple "solutions": sending bytes, JSON in string, request headers, WWW, but none of them seem to work.

POST part in API controller

    // POST: api/Todo
    [HttpPost]
    public async Task<ActionResult<LeaderboardItem>> 
    PostLeaderboardItem(LeaderboardItem item)
    {
        _context.LeaderboardItems.Add(item);
        await _context.SaveChangesAsync();

        return CreatedAtAction(nameof(GetLeaderboardItem), new { id = item.Id }, item);
    }

UnityWebRequest

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using UnityEngine.Networking;

[Serializable]
public class MiniGame
{
public int id;
public int teamId;
public int score;
}

public class JSON_Test : MonoBehaviour
{
void Start()
{
    MiniGame miniGame = new MiniGame();
    miniGame.id = 9999;
    miniGame.teamId = 10;
    miniGame.score = 10;

    StartCoroutine(PostRequest(miniGame));
}

public IEnumerator PostRequest(MiniGame miniGame)
{
    string jsonData = JsonUtility.ToJson(miniGame);
    Debug.Log(jsonData);

    using (UnityWebRequest request = 
UnityWebRequest.Get("https://localhost:44326/api/leaderboard"))
    {
        request.method = UnityWebRequest.kHttpVerbGET;
        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("Accept", "application/json");
        yield return request.SendWebRequest();
        //if (!request.isNetworkError && request.responseCode == (int)responseCodes.OK)
        //{
        //    Debug.Log("Data succesfully sent to the server");
        //}
        //else
        //{
        //    Debug.Log("Error sending data to the server");
        //}
    }
   }
 }

Any help?

Kevin
  • 31
  • 2

2 Answers2

0

I have some simular problem with get request from asp core web api. Solution for me was use http instead https for web api

Dmitri
  • 1
  • 1
-1

UnityWebRequest.Get("https://localhost:44326/api/leaderboard"))

Try using your local ip address, instead of localhost.

gmaziashvili
  • 250
  • 1
  • 19