简体   繁体   English

Web API:FromBody 始终为空

[英]Web API: FromBody always null

I'm trying to develop a web API, and when I test the POST method, the body is always null.我正在尝试开发一个 Web API,当我测试 POST 方法时,主体始终为空。 I have tried everything when sending the request:发送请求时我已经尝试了一切:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:1748/api/SomeAPI");
req.Method = "post";;

var aaa = Encoding.Default.GetBytes("Test");
req.ContentType = "application/xml";
req.ContentLength = aaa.Length;
req.GetRequestStream().Write(aaa, 0, aaa.Length);

HttpWebResponse res = (HttpWebResponse)req.GetResponse();
using (System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream())) {
    Console.WriteLine(sr.ReadToEnd());
}

I use a breakpoint, and the API is called properly, but the body member is always null:我使用了断点,并且正确调用了 API,但是 body 成员始终为 null:

[HttpPost]
public void Post([FromBody]String test) {

}

Your Content Type is set to XML so you must pass the data as XML.您的内容类型设置为 XML,因此您必须将数据作为 XML 传递。 This means wrapping your data in <string> element.这意味着将您的数据包装在<string>元素中。

I would recommend using RestSharp ( http://restsharp.org/ ) for making WebAPI calls from .Net.我建议使用 RestSharp ( http://restsharp.org/ ) 从 .Net 进行 WebAPI 调用。

        var client = new RestClient("http://localhost:1748/");
        var request = new RestRequest("api/SomeAPI", Method.POST);
        request.AddBody("Test");
        var response = client.Execute(request);

Update更新

I have created a sample project and it works absolutely fine:我创建了一个示例项目,它工作得非常好:

Server side:服务器端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;

namespace WebApplication1.Controllers
{
    public class HomeController : ApiController
    {
        [Route("api/TestAPI")]
        [HttpPost]
        public IHttpActionResult Post([FromBody]String test)
        {
            return Ok(string.Format("You passed {0}.", test));
        }
    }
}

Client side:客户端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:1748/api/TestAPI");
            req.Method = "post"; ;
            var aaa = Encoding.Default.GetBytes("\"Test\"");
            req.ContentType = "application/json";
            req.ContentLength = aaa.Length;
            req.GetRequestStream().Write(aaa, 0, aaa.Length);
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            using (System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream()))
            {
                Console.WriteLine(sr.ReadToEnd());
            }
        }
    }
}

After installing the WEB API service in IIS and running the console app it prints:在 IIS 中安装 WEB API 服务并运行控制台应用程序后,它会打印:

"You passed Test."

Please note the quotes around the response.请注意响应周围的引号。 If you want to use XML then you need to modify the content type and data you are sending:如果要使用 XML,则需要修改要发送的内容类型和数据:

var aaa = Encoding.Default.GetBytes("<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Test</string>");

The response you will get is你会得到的回应是

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">You passed Test.</string>

Both samples in the debugger will have correct value passed in the test parameter.调试器中的两个样本都将在测试参数中传递正确的值。

try试试

[HttpPost]
public void SomeApi()
{
   var test = HttpContext.Current.Request.Form["Test"];
}

If u send correctly the value,this will work 100%如果您正确发送值,这将 100%

Two things to try, 1st, try your request using a tried and tested tool like Postman.有两件事要尝试,第一,使用像 Postman 这样久经考验的工具来尝试您的请求。 This will eliminate any chance your request is malformed in any way.这将消除您的请求以任何方式格式错误的任何机会。 2nd, try changing your ContentType to text/plain.第二,尝试将您的 ContentType 更改为 text/plain。 It's possible the request pipeline is seeing application/xml but your request body is invalid xml which really should be a bad request but is just being serialized as null.请求管道可能正在查看 application/xml 但您的请求正文是无效的 xml,这确实应该是一个错误的请求,但只是被序列化为 null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM