首页 > 解决方案 > 在 C# 的控制器中读取 POST 请求的请求正文

问题描述

我正在对 API 实现进行原型设计,但遇到了一个基本问题,即无法读取JSON我在请求正文中传递的对象Fiddler。我的实现基于我在不同初学者教程中找到的一些示例。

这是我对 API 的调用:

https://{Something}/servername/{something1}/checkAvailability?{api-version}

这是一个POST请求,请求正文是(JSON):{name:"resource1", option:"include"}

我试图在控制器上解析它的方式是使用 [FromBody]。但是,[FromBody] 参数始终被读取为 null:

    [HttpPost]
    // A bunch of other attributes.
    public HttpResponseMessage CheckAvailability(
        string serverName,
        [FromBody] CheckProperties props)
    {
        // While debugging, I am able to reach here and successfully see the serverName as "something1" which passed in the API
        if (serverName == null || serverName == "")
        {
            return CreateResponse(HttpStatusCode.BadRequest);
        }

        // Able to reach here but the value of props is read as null. What is the right way to read the request body in props(CheckNameProperties) object?
        if (props != null) // props is always null for me.
        {
            // Do something
        }
  }

检查属性.cs

public class CheckProperties
    {
        [JsonProperty]
        public string Name{ get; set; }

        [JsonProperty]
        public string Option { get; set; }

        public CheckProperties(string name, string options)
        {
            Name = name;
            Option = options;
        }
    }

我没有使用对象,而是尝试读取一个简单的字符串。但是,也读不出来。

此外,如果有人可以分享帮助他们对实现 API 有很好的基本了解的教程,那就太好了。我遇到的大多数教程都在讨论 API 设计原则,而不是实现它的方法。

标签: c#asp.net-web-apiapi-designasp.net-web-api-routing

解决方案


推荐阅读