【问题标题】:WebAPI postman not calling PostWebAPI 邮递员不调用 Post
【发布时间】:2020-03-17 23:29:30
【问题描述】:

我在控制器上有一个帖子,我不能用帖子调用,我看不到我做错了什么。

 [RoutePrefix("api/camps")]
 public class CampsController : ApiController

  [Route()]
  public async Task<IHttpActionResult> Get()
  {
      //Return list
  }


  [Route()]
  public IHttpActionResult Post(object model)
  {
       throw new NotImplementedException();
  }

当我在 Visual Studio 中运行应用程序并在 Postman 中调用 post 时 http://localhost:6600/api/camps 我得到了返回的预期列表,并且在设置断点时,一切都会被击中,这是我所期望的。

当我使用 http://localhost:6600/api/camps 调用 Post 时,我输入了 Body 和 Raw in postman。

{

    "Name": "Mr A",
}

我得到了 post 方法,但类型对象的模型是空白的。 如果我将模型更改为 camp 类型,则该模型的每个属性都为空。 我已经改变了所有的情况,并添加和删除了双引号和单引号。

我的 WebApiConfig

 public static class WebApiConfig
  {
    public static void Register(HttpConfiguration config)
    {     

        //Changes names on result to be camel case not what they are in the model.
        config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        //For binding to models when passing in data
      config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));

        // Web API routes
        config.MapHttpAttributeRoutes();


}

【问题讨论】:

    标签: asp.net-web-api asp.net-web-api2 postman


    【解决方案1】:

    使用您想要的属性创建一个类,如下所示:

    public class Your_Class
        {
            public string Name { get; set; }
            //...Your other properties if any
    
        }
    

    现在在您的 API 中使用这个模型类作为参数。

      [Route()]
      public IHttpActionResult Post(Your_Class model)
      {
           throw new NotImplementedException();
      }
    

    更新

    对于仍然面临此问题的其他人,请确保在发送请求之前在 postman 中的 header 部分中将 Content-Type 设置为 application/json

    【讨论】:

    • 我在问题中说过“如果我将模型更改为 camp 类型,则它的每个属性都为空。”
    • 在发送请求之前尝试在 postman 中将 headers 设置为 Content-Type as application/json。
    • 这就是答案,谢谢,如果你想发布它,我会将它标记为答案
    • 感谢您的确认,我已经更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2016-04-03
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多