weixin_40576400
2021-10-13 14:53
采纳率: 84%
浏览 67

WebApi无法读取传入的POST字符串参数

WebApi无法读取传入的POST字符串参数,也就是调用这个WebApi的代码中不论给code0传入什么字符串,WebApi读到的code0都是空值。希望各位专家能够给与指点迷津!
也就是执行完string code = code0;后,code无法获取code0的值,也就是code0根本就没有传进来。

我的WebApi代码如下:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace expressApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SurfaceController : ControllerBase
    {
        public List<TechnicalRequirement> TechnicalRequirements = new List<TechnicalRequirement>();       
        [HttpPost("PostSurface")]
        public IActionResult Surface([FromForm] string code0)
        {
            string code = code0;
           if (TechnicalRequirements == null)
            {
                        return NotFound();
            }
            return Ok(TechnicalRequirements);
     }
}

我用于测试调用这个WebApi的代码如下(初步认为不会是下面的代码的问题,因为别人用JAVA写的程序一样无法传入参数):


```c#
string strUri = requestUri;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUri);
            request.Method = "POST";
            //request.ContentType = "text/plain";
            request.ContentType = "application/x-www-form-urlencoded";//form值的代码,只要修改req.ContentType = "application/x-www-form-urlencoded//application/json
            string paraUriCoded = json;
            byte[] payload;
            payload = System.Text.Encoding.UTF8.GetBytes(paraUriCoded);
            request.ContentLength = payload.Length;
            Stream writer;
            try
            {
                writer = request.GetRequestStream();
            }
            catch (Exception ex)
            {
                return ex.ToString();                
            }
            writer.Write(payload, 0, payload.Length);
            writer.Close();
            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }
            Stream s = response.GetResponseStream();
            StreamReader sRead = new StreamReader(s);
            string postContent = sRead.ReadToEnd().ToString();
            sRead.Close();
            return postContent;

```

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题