简体   繁体   中英

How I can show null value in the response from a POST request?

I have a POST: localhost:10411/api/channel -> to create channel with request body:

"cut": {
{
"title": "track 200-1",
"duration": "00:00:30",
"album": "album 200-1",
"logoUrl":null
},
{
"title": "track 200-2",
"duration": "00:00:30",
"album": "album 200-2",
"logoUrl": "this is a text"
},
{
"title": "track 200-3",
"duration": "00:00:30",
"album": "album 200-3",
}
}

I want when:

  1. no logoUrl provided -> it will generate image;

  2. logoUrl string provided -> use text in the response;

  3. logoUrl null provided -> use null in the response;

However, the response I received is only statisfy the 1) and 2) condition. I cannot get the 3) working. Here is the response:

{
"title": "track 200-1",
"album": "album 200-1",
"url": "localhost:10411/api/logos/album%200-1" (I want here show url = null instead of showing auto generate logo)
},
{
"title": "track 200-2",
"album": "album 200-2",
"url": "this is a text" (showing string, worked as expected)
},
{
"title": "track 200-3",
"duration": "00:00:30",
"album": "album 200-3",
"url": "localhost:10411/api/logos/album%200-3" (showed auto generate logo when not specify logoUrl in the request body, worked as expected)
}

Here is my mapping and the function:

CreateMap<Cut, CutData>()
   .ForMember(
       dest => dest.Album,
       opt => opt.MapFrom(scr => GetAlbum(scr.Channel.BaseUrl, src.LogoUrl, src.Album)));

private Album GetAlbum(string baseUrl, string customUrl, string albumName)
{
  Album album = new Album(baseUrl, albumName);
  if(customUrl != null)
  {
    image.Url = customUrl;
  }

  return album;
}

You guys please help me how I can distinguish the case when I didn't specify logoUrl in the request body (logoUrl is totally absent.) ->it will generate auto logo which is working well now. The case when I specify logoUrl = null -> I want it show in the response null instead of showing auto logo. Thank you very much for your help. Sincerely appreacited!

Unfortunately you can't. When you send an object to an API. Any value not provided will be automatically become the default value - for a string that's null . Meaning:

{
   "title": "track 200-1",
   "duration": "00:00:30",
   "album": "album 200-1",
   "logoUrl":null
}

And

{
   "title": "track 200-2",
   "album": "album 200-2",
   "url": "this is a text" 
}

Are the same.

If you really want a third value you can put logoUrl: "" . That way you can say something like:

if (logoUrl == null) {/* Do Work */}
if (logoUrl.Length == 0) {/* Do Work */}
if (logoUrl.Length > 0) {/* Do Work */}

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