POST throws HttpRequestMessage不包含Form的定义

本文关键字:Form 定义 包含 throws HttpRequestMessage POST | 更新日期: 2023-09-27 18:00:12

我正在尝试在C#中获取POST数据,我读到的所有内容都说要使用

Request.Form["parameterNameHere"]

我正在尝试,但我得到一个错误说

System.Net.Http.HttpRequestMessage不包含Form的定义,也没有Form的扩展方法。'

有问题的方法是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.HttpRequest;
namespace TextServer.Controllers
{
public class TextController : ApiController
{
    // POST api/<controller>
    public HttpResponseMessage Post([FromBody]string value)
    {
        string val = Request.Form["test"];
        HttpResponseMessage response = new HttpResponseMessage();
        response.Content = new StringContent("Your message to me was: " + value);
        return response;
    }

非常感谢您的帮助。

POST throws HttpRequestMessage不包含Form的定义

您应该在请求正文中传递对象,并从正文中检索值:

public HttpResponseMessage Post([FromBody] SomeModel model)
{
    var value = model.SomeValue;
    ...

或者,如果你只需要字符串:

public HttpResponseMessage Post([FromBody] string value)
{
    HttpResponseMessage response = new HttpResponseMessage();
    response.Content = new StringContent("Your message to me was: " + value);
    return response;
}