我可以将 ASP.Net WebApi 用于 Unity Server 吗?

问题描述 投票:0回答:1

我创建了一个统一的项目,其中从用户处获取数据,然后以 csv 格式保存在设备中。现在,我正在寻找一种将这些数据上传到服务器的方法。出于服务器目的,我使用 ASP.Net 的 WebAPI。我已经创建了一个合适的 WebAPI 并使用 Swagger 对其进行了检查。现在,当我运行代码时,我不确定,数据是在 WebAPI 项目打开时从 Unity 传递的,但是当 WebAPI 项目打开时,它显示空值,因为那里没有更新文件。

我尝试过不同的方式和文件从Unity发布。 字符串文件

private IEnumerator UploadStringCoroutine() 
{
 string stringValue = "Hello World"; // The string value to send
 using (UnityWebRequest www = new UnityWebRequest(serverUrl, "POST"))
 {
   byte[] stringBytes = System.Text.Encoding.UTF8.GetBytes(stringValue);
   www.uploadHandler = new UploadHandlerRaw(stringBytes);
   www.downloadHandler = new DownloadHandlerBuffer(); // Set the content type header to indicate plain text
   www.SetRequestHeader("Content-Type", "text/json");
   yield return www.SendWebRequest();
   if (www.result == UnityWebRequest.Result.Success) 
    { 
      Debug.Log("String data uploaded successfully!");
      Debug.Log("Server response: " + www.downloadHandler.text);
    }
   else
    {
      Debug.LogError("Failed to upload string data. Error: " + www.error);
    }
 }
} 

CSV 文件内容

    private IEnumerator UploadCSVCoroutine(string filePath)
    {
        // Read the content of the CSV file as binary data
        byte[] csvBytes = File.ReadAllBytes(filePath);

        // Create a UnityWebRequest to POST the binary data to the server
        UnityWebRequest www = new UnityWebRequest(serverUrl, "POST");
        UploadHandlerRaw uploadHandler = new UploadHandlerRaw(csvBytes);
        www.uploadHandler = uploadHandler;
        www.downloadHandler = new DownloadHandlerBuffer();

        // Set the content type to indicate binary data
        www.SetRequestHeader("Content-Type", "multipart/form-data");

        // Send the request
        yield return www.SendWebRequest();

        // Check the result of the request
        if (www.result == UnityWebRequest.Result.Success)
        {
            Debug.Log("CSV file uploaded successfully!");
            Debug.Log("Server response: " + www.downloadHandler.text);
        }
        else
        {
            Debug.LogError("Failed to upload CSV file. Error: " + www.error);
        }
    }

我也尝试将 csv 转换为 json,但我得到了相同类型的错误。这是在Controller.cs中编写的WebApi解决方案中的代码

        [HttpPost("read-employee-csv")]
        public IActionResult GetEmployeeCSV([FromBody] string csvContent)
        {
            byte[] csvBytes = Encoding.UTF8.GetBytes(csvContent); // Convert the content to bytes
            var stream = new MemoryStream(csvBytes); // Create a MemoryStream

            var employees = _csvService.ReadCSV<Coordinate>(stream); // Pass the MemoryStream

            return Ok(employees);
        } 

CSVService.cs 文件包含以下代码,由上面代码中的 _csvService 调用

        public IEnumerable<T> ReadCSV<T>(Stream file)
        {
            try
            {
                var config = new CsvConfiguration(CultureInfo.InvariantCulture);
                using var reader = new StreamReader(file);
                using var csv = new CsvReader(reader, config);

                // Read and parse the CSV data into a strongly-typed IEnumerable<T>
                return csv.GetRecords<T>();
            }
            catch (Exception ex)
            {
                // Handle any exceptions or validation errors here
                throw ex;
            }

老实说,我对服务器上传一无所知,无论是在 unity 还是 webapi 中,我都是根据搜索后得到的信息进行编码的。我知道代码中存在错误,但我不知道它们是什么,而且我在这个问题上停留了很长时间,所以很少的帮助和指导会很棒。如果 WebAPI 有其他方法,请告诉我。任何形式的帮助都是伟大的。如果我问了任何愚蠢的问题,请原谅我,因为我已经因此而伤透了我的大脑。 :-(

rest csv unity-game-engine asp.net-web-api server
1个回答
0
投票

我给出了一个简单的解决方案,说明如何使用 Web Api 将数据从 Unity 发送到后端 mysql 数据库。

统一代码

private IEnumerator UploadStringCoroutine() 
{
 string stringValue = "Hello World"; // The string value to send
 string serverURL = "Your API URL";
 WWWForm form = new();
 form.AddField("value", stringValue);

 UnityWebRequest webRequest = UnityWebRequest.Post(uri, form);
 webRequest.downloadHandler = new DownloadHandlerBuffer();
 yield return webRequest.SendWebRequest();
 if (www.result == UnityWebRequest.Result.Success)
   {
    Debug.Log("File uploaded successfully!");
    Debug.Log("Server response: " + www.downloadHandler.text);
   }
 else
   {
    Debug.LogError("Failed to upload File. Error: " + www.error);
   }
}

API代码

[HttpPost]
[Route("Your API URL")]
public IActionResult methodName([FromForm] string value)
 {
  return Ok("Value Fetched " + value);
 }

对于CSV文件数据,我已经使用Newtonsoft.Json包将数据转换为json字符串文件

string jsonFile = JsonConvert.SerializeObject(csv_file_data);
并以同样的方式转换回字符串。

这对我的数据共享很有帮助。希望对你也有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.