为什么添加此构造函数会导致我的API在C#中工作?

时间:2018-06-28 13:37:09

标签: c# asp.net api constructor content-type

我有以下代码:

[HttpPost]
[Route("createRepo")]
public HttpResponseMessage createRepo(GitHub githubInfo)
{
    return new HttpResponseMessage(HttpStatusCode.OK)
    {
    Content = new StringContent(githubInfo.RepoName, System.Text.Encoding.UTF8, "application/json")
    };
}

仅在上面,我有一个POST路由,该路由需要一个Github对象作为输入,并仅返回该对象中提供的repoName

这是Github模型类:

public class GitHub {
    public string RepoName { get; set; }
    public string Organization { get; set; }

    public GitHub(string RepoName, string Organization) {
        this.RepoName = RepoName;
        this.Organization = Organization;
    }
}

现在,使用表单主体执行POST请求会返回错误:

Elements

这意味着githubInfo为空,因此您无法访问其名为RepoName的属性。

但是,如果我在模型GitHub类中添加以下行:

public GitHub() { }

制作整个模型:

public class GitHub {
    public string RepoName { get; set; }
    public string Organization { get; set; }

    public GitHub(string RepoName, string Organization) {
        this.RepoName = RepoName;
        this.Organization = Organization;
    }

    public GitHub() { }
}

然后我有一个不同的故事:

enter image description here

它实际上识别输入,并且能够打印出属性名称。为什么?添加此空构造函数有什么意义?

2 个答案:

答案 0 :(得分:1)

默认的MVC模型联编程序对您的类一无所知,因此不了解构造函数。因此,它需要一个无参数的构造函数才能实例化模型并填充属性。

答案 1 :(得分:0)

由于默认情况下,实例化对象,因此框架使用简单的无参数构造函数,并使用设置方法填充属性。

(这很有意义,恕我直言,它按预期工作,并且避免了很多思考来尝试猜测哪个构造函数是适当的,没有明显的收获)

请注意,有时 可能没有引起注意,如果您未明确定义任何构造函数,则默认情况下将创建无参数的公共构造函数。

但是,只要您指定另一个构造函数,就不会创建默认的无参数构造函数。