c# – POST throws HttpRequestMessage不包含Form的定义

我试图用C#获取POST数据,我读过的所有内容都说要使用

Request.Form["parameterNameHere"]

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

System.Net.Http.HttpRequestMessage does not contain a definition for Form and no extension method for 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;
    }

任何帮助是极大的赞赏.

最佳答案 您应该在请求正文中传递您的对象并从正文中检索值:

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;
}
点赞