简体   繁体   English

Web API C# 中的 POST 请求

[英]POST request in Web API C#

I'm new in working with ASP.net.我是 ASP.net 的新手。 I have problem with POST request.我有 POST 请求的问题。 Perhaps my code is wrong, I don't find where !也许我的代码是错误的,我没有找到哪里!

Postman sends me the error message when I try a post request :当我尝试发布请求时,邮递员向我发送错误消息:

"ExceptionType":"System.Net.Http.UnsupportedMediaTypeException","StackTrace":" à System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable 1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\\r\\n à System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable 1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"} "ExceptionType":"System.Net.Http.UnsupportedMediaTypeException","StackTrace":" à System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable 1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\\r\\n à System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable 1 formatters, IFormatterLogger formatterLogger, CancellationToken cancelationToken)"}

Here is my code :这是我的代码:

// POST: api/Boooks
[Route("~/api/PostCreate")]
public IHttpActionResult Post([FromBody] Books books)
{
    if (!ModelState.IsValid)
        return BadRequest("Invalid data.");

If you left it at default, then you will probably find that you need to set the application content type in post man as part of your headers info.如果您将其保留为默认值,那么您可能会发现需要在 post man 中设置应用程序内容类型作为标题信息的一部分。

By Default I think asp.net core expects the content type to be of application/json.默认情况下,我认为 asp.net core 期望内容类型为 application/json。 and your post man call is most likely sending it as text/html.并且您的邮递员电话很可能以 text/html 的形式发送。

See your headers sent, make the changes and see the results.查看您发送的标头,进行更改并查看结果。

Check your request headers in Postman!在 Postman 中检查您的请求标头!

在 Postman 中检查您的请求标头

You should not have to change anything in the c# code, it should accept JSON by default.您不必更改 c# 代码中的任何内容,默认情况下它应该接受 JSON。

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

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