首页 文章

将数据从字符串值发布到 asp net core web api 控制器方法

提问于
浏览
2

我有一个带有 REST 控制器的 Asp Net Core 2.1 应用程序,如下所示:

[Produces("application/json")]
[Route("api/Test")]
public class TestController : Controller
{
    // GET: api/Test
    [HttpGet]
    public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }

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

    // POST: api/Test
    [HttpPost]
    public void Post([FromBody]string value)
    {
        //.. testing code..
    }

    // PUT: api/Test/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value) {}

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

我正在尝试使用“System.Net.HttpWebRequest”对象向 Rest 控制器发出 POST 请求。在我的客户端应用程序中,我有一个以字符串形式接收数据的方法。
字符串内容是一个动态数组值,例如“param1=value1; param2=value2”(元素数量是可变的)。
你能帮我理解将这些数据发送到控制器的正确方法吗?

这是我试图在客户端中使用的代码:

public static string PostWebApi(string postData)
{    
    var request = (HttpWebRequest)WebRequest.Create("http://localhost:64817/api/test");

    // for example, assumes that postData value is "param1=value1;param2=value2"
    var data = Encoding.ASCII.GetBytes(postData);

    request.Method = "POST";
    request.ContentType = "application/json";
    //request.ContentType = "application/x-www-form-urlencoded";

    request.ContentLength = data.Length;

    using (var stream = request.GetRequestStream()) {
        stream.Write(data, 0, data.Length);
    }

    var response = (HttpWebResponse)request.GetResponse();
    var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

    return responseString;
}

我正在使用内容类型“application/json”:如果我尝试使用“application/x-www-form-urlencoded”,我会收到“(415)不支持的媒体类型”错误。
所以......当我执行 PostWebApi 时,我在 POST 中收到一个 Null 值参数:api/Test 方法..
我怎样才能收到我发送的数据?

提前致谢。

1 回答

  • 2

    你可以使用 HTTPClient。它会为你缓解这个过程。

    public static string PostWebApi(string postData)
    {           
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:64817/api/test");
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("value", postData)
                });
                var result = await client.PostAsync("/api/Membership/exists", content);
                string resultContent = await result.Content.ReadAsStringAsync();
                Console.WriteLine(resultContent);
            }
    }
    

    参考: - 如何进行 HTTP POST Web 请求

相关问题