我在.Net Core 2.1中有一个简单的Web服务。我想从Unity 3D发布,但是它不起作用

时间:2019-04-20 06:29:13

标签: c# .net json web-services unity3d

我想从Unity3d发布到基于.Net Core 2.1的Web服务(RESTFUL)。 GET有效,POST不起作用。

我收到了

  

{       “”:[           “解析值:{。Path”,第1行,位置1时遇到意外字符。”       ]   }

我也尝试更改RequestHeader,但是它不起作用。

通过使用单独的.Net客户端,以下代码有效。

HttpClient().PostAsJsonAsync(weblink,SerializedData)

PostAsJsonAsync背后是什么“魔术”?

在Unity3D中,我无法使用HttpClient的扩展名。

这是Unity3d中的代码

    void Start()
    {
        StartCoroutine(postUnityWebRequest());
    }

    IEnumerator postUnityWebRequest()
    {
        ///<summary>
        /// Post using UnityWebRequest class
        /// </summary>
        var jsonString = "{\"Id\":3,\"Name\":\"Roy\"}";
        byte[] byteData = System.Text.Encoding.ASCII.GetBytes(jsonString.ToCharArray());

        UnityWebRequest unityWebRequest = new UnityWebRequest("http://localhost:2071/api/Commands?Id=1", "POST");
        unityWebRequest.uploadHandler = new UploadHandlerRaw(byteData);

        unityWebRequest.method = UnityWebRequest.kHttpVerbPOST;
        unityWebRequest.SetRequestHeader("Content-Type", "application/json");
        unityWebRequest.SetRequestHeader("Accept", "application/json"); 
        yield return unityWebRequest.SendWebRequest();

        if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
        {
            Debug.Log(unityWebRequest.error);
        }
        else
        {
            Debug.Log("Form upload complete! Status Code: " + unityWebRequest.responseCode);
        }
    }

这是Web服务的代码。

namespace WebService.Controllers
{
    [Route("api/[controller]")]
    [ApiController]


    public class CommandsController : ControllerBase
    {

        private static List<string> commandToBeExecuted = new List<string>();

        // GET: api/Commands
        [HttpGet]
        public string Get()
        {
            if (commandToBeExecuted.Count > 0)
            {
                string output = commandToBeExecuted.First();
                commandToBeExecuted.RemoveAt(0);
                return output;
            }

            return "-1";

        }

        // GET: api/Commands/5
        [HttpGet("{id}", Name = "Get")]
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/Commands
        [HttpPost]
        public void Post([FromBody] string value)
        {
            commandToBeExecuted.Add(value);
        }

        // PUT: api/Commands/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
            int debugShouldStopHere = 0;
        }

        // DELETE: api/ApiWithActions/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }

0 个答案:

没有答案