简体   繁体   中英

ASP.NET omit specific variable in response?

In ApiController subclass,

[HttpGet]
public HttpResponseMessage api()
{
 //somecode 
 Res res = new Res();
 return Request.CreateResponse(200, res);

}

And Res class,

public class Res{
Public Meta meta{get;set;}
Public Data data{get;set;}
}

In case of some http status code such as 401, 500, I want to omit data variable.

200 ok

{ meta:{...}, data:{...}}

500 internal server error { meta:{...}}

How to omit data variable? remove variable in class? use ExpandoObject()?

You could use:

public class Res{

    Public Meta meta{get;set;}

    [JsonIgnore]
    Public Data data{get;set;}
}

Or, decorate the ones you want...

[DataContract]
public class Res{

    [DataMember]  
    Public Meta meta{get;set;}

    Public Data data{get;set;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM