首页 > 解决方案 > Web api 只返回一些字段

问题描述

以下 api 函数返回 PartnerApiModel 对象,这很好。

[HttpGet]
public HttpResponseMessage Get()
{
   PartnerAPIModel apiPartner = new PartnerAPIModel();
   apiPartner.PublicId = "1";
   apiPartner.DisplayName = "Show this";
   apiPartner.Name = "Test";

   return Request.CreateResponse(HttpStatusCode.OK, apiPartner);
}

结果:

{
    "PublicId": "7eda5b39-7ef8-ea29-6136-37701e05b0cc",
    "DisplayName": "Show this",
    "Name": "Test",
}

是否可以仅返回以下内容?

{
    "PublicId": "7eda5b39-7ef8-ea29-6136-37701e05b0cc",
    "DisplayName": "Show this",
}

标签: c#webapi

解决方案


用 jsonIgnore 标记要忽略的属性:

using Newtonsoft.Json;
public class PartnerApiModel {
    [JsonIgnore]
    public string Name {get; set;}
}

推荐阅读