网络 API 未在 POST 上读取我的类型

Web API is not reading my type on POST

我正在尝试通过 POST 将一些数据发送到我的 Web API,但我的数据始终被读取为空。

我将其作为表单数据发送

Content-Type: application/x-www-form-urlencoded

它在我的另一个项目中工作,但在这里却没有,这很奇怪。

我的类型是这样的:

public class QueryResult
{
    public List<string> Headers;
    public List<QueryResultLine> Results;
}

我的要求是这样的:

[Route("export/excel")]
public HttpResponseMessage PostExportToExcel(QueryResult queryResult)
{
    DoSomething(queryResult);
}

每当我发出此请求时 queryResult.Headers 并且 queryResult.Results 为空。

Headers=%5B%22Nummer%22%2C%22Omschrijving%22%2C%22Locatie%22%2C%22Beheerder%22%2C%22Niveau%22%2C%22ArtikelNummer%22%2C%22Naam%22%2C%22InhoudL%22%2C%22InhoudKG%22%2C%22Voorkomen%22%2C%22Opslag%22%2C%22Seveso%22%2C%22CLP%22%2C%22Uitvoering%22%2C%22Voorziening%22%2C%22HPZinnen%22%5D&Results=%5B%7B%22Nummer%22%3A%22DECO.1%22%2C%22Omschrijving%22%3A%22Testvat%22%2C%22Locatie%22%3A%22Testvat+chem%22%2C%22Beheerder%22%3A%22SIDCCEO%22%2C%22Niveau%22%3A0%2C%22ArtikelNummer%22%3A%22AM00632548%22%2C%22Naam%22%3A%22Tetrahydrothiophene+-+Scentinel++T+Gas+Odorant%22%2C%22InhoudL%22%3A150%2C%22InhoudKG%22%3A150%2C%22Voorkomen%22%3A%22verplaatsbaar+recipi%C3%ABnt%22%2C%22Opslag%22%3Afalse%2C%22Seveso%22%3A%22P5c%22%2C%22CLP%22%3Anull%2C%22Uitvoering%22%3A%22%22%2C%22Voorziening%22%3A%22%22%2C%22HPZinnen%22%3A%22H312%2C+H315%2C+H332%2C+P280%2C+P501%2C+H302%2C+H225%2C+H319%2C+H412%2C+P210%2C+P233%2C+P240%2C+P241%2C+P242%2C+P243%2C+P264%2C+P270%2C+P301%2B310%2C+P303%2B361%2B353%2C+P330%2C+P331%2C+P370%2B378%2C+P403%2B235%2C+P405%22%2C%22%24%24hashKey%22%3A%22object%3A210%22%7D%5D

Whenever I make this request queryResult.Headers and queryResult.Results is null

HeadersResults 在模型绑定期间未绑定,因为它们被声明为字段,而不是属性。默认模型绑定器将仅绑定属性。检查 this article 了解更多详情。

所以你应该将 QueryResult 的定义调整为:

public class QueryResult
{
    public List<string> Headers { get; set; }

    public List<QueryResultLine> Results { get; set; }
}

对于您提供的查询正文,Headers 属性 将被反序列化为一个包含一个字符串的列表,即

["Nummer","Omschrijving","Locatie","Beheerder","Niveau","ArtikelNummer","Naam","InhoudL","InhoudKG","Voorkomen","Opslag","Seveso","CLP","Uitvoering","Voorziening","HPZinnen"]

我相信这不是您所期望的,您需要将所有这些值作为单独的字符串添加到列表中。 为此,您应该修复从客户端发送的请求。以下请求正文将被正确反序列化为值列表:

Headers=Nummer&Headers=Omschrijving&Headers=Locatie&Headers=Beheerder&Headers=Niveau&Headers=ArtikelNummer&Headers=Naam&Headers=InhoudL&Headers=InhoudKG&Headers=Voorkomen&Headers=Opslag&Headers=Seveso&Headers=CLP&Headers=Uitvoering&Headers=Voorziening&Headers=HPZinnen

如您所见,为了构建列表,Headers 只是用不同的值重复。 Results 的请求部分应按相同方式调整。