简体   繁体   中英

WebApi - Convert null string into null value

What is the best way to convert a 'null' string (passed into a url) to a null value in WebApi using attribute routing?

Url sample:

localhost:29365/api/myController/Test/first/null/third

Api Controller Method sample:

[HttpGet]
[Route("~/api/MyController/Test/{first}/{second}/{third}")]
public void Test(string first, string second, string third)
{ ... }

Well your only option would be comparing if the string value is null. However this seems terrible.

Why not try passing as parameters instead.

[HttpGet]
[Route("~/api/MyController/Test")]
public void Test(string first = null, string second = null, string third = null)
{ ... }

URL Sample

localhost:29365/api/myController/Test?first=myfirstvalue&third=mythirdvalue

By not supplying the second value it is null by default.

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