从httpresponsemessage中删除一些对象属性



我有一个名为CatalogSourceCodeItemsResponse的类。这就是它的定义:

public partial class CatalogSourceCodeItemsResponse  
 {
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private MMS.LoyaltyNext.API.SpendCard.MARSCatalog.CatalogFeed[] catalogFeedField;
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string endDateField;
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string sourceCodeField;
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string startDateField;
}

注意我无法修改/更新类,因为它来自服务。

我创建了一个web api,它向服务发出请求,并将此类作为响应返回。我的要求是,我只需要第一个,而不是归还所有的财产。

这是返回响应的代码:

[HttpGet]
        public HttpResponseMessage GetCatalogItems()
        {
            CatalogSourceCodeItemsResponse response = new CatalogSourceCodeItemsResponse();
            response = //logic to return the response from the service
            return Request.CreateResponse<CatalogSourceCodeItemsResponse>(HttpStatusCode.OK, response);
        }

当前输出为

{
    "catalogFeed" : null,
    "endDate" : null,
    "sourceCode" : null,
    "startDate" : null
}

所需输出为

{
    "catalogFeed" : null
}

我怎样才能做到这一点?

您可以使用ViewModel。

视图模型仅表示要在视图/页面上显示的数据,无论是用于静态文本还是用于输入值(如文本框和下拉列表)

 public partial class CatalogSourceCodeItemsResponse  
 {
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private MMS.LoyaltyNext.API.SpendCard.MARSCatalog.CatalogFeed[] catalogFeedField;
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string endDateField;
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string sourceCodeField;
        [System.Runtime.Serialization.OptionalFieldAttribute()]
        private string startDateField;
}

视图模型与域模型的不同之处在于,视图模型只包含要在视图中使用的数据(由属性表示)。例如,假设您只想在CatalogSourceCodeItemsResponse记录中显示一个项目,那么您的视图模型可能如下所示:

public class CatalogSourceCodeItemsResponseViewModel
{
     private MMS.LoyaltyNext.API.SpendCard.MARSCatalog.CatalogFeed[] catalogFeedField; { get; set; }
}

然后你的控制器动作将变成

    [HttpGet]
            public HttpResponseMessage GetCatalogItems()
            {
                CatalogSourceCodeItemsResponse response = new CatalogSourceCodeItemsResponse();
                response = //logic to return the response from the service
                CatalogSourceCodeItemsResponseViewModel responseViewModel=new CatalogSourceCodeItemsResponseViewModel();
                responseViewModel.catalogFeedField=response.catalogFeedField;
                 return Request.CreateResponse<CatalogSourceCodeItemsResponseViewModel>(HttpStatusCode.OK, responseViewModel);
            }

相关内容

  • 没有找到相关文章

最新更新