letsar / DoLess.UriTemplates

.Net Standard implementation of the URI Template Spec https://tools.ietf.org/html/rfc6570
MIT License
14 stars 1 forks source link

[Question] How to disable encoding for segments with a forward slash #3

Closed DoCode closed 6 years ago

DoCode commented 6 years ago

How can I disable the encoding for path segments with a forwarding slash inside?

Template:

http://localhost/resource1{/resource2}{?q,pageindex,pagesize}

the data:

resource2 = "path/to/my/resource"
pagesize = 10

should result in

http://localhost/resource1/path/to/my/resource?pagesize=10
letsar commented 6 years ago

Hi @DoCode. For this You should use the + operator instead of the / one:

UriTemplate.For("http://localhost/resource1/{+resource2}{?q,pageindex,pagesize}")
           .WithParameter("resource2", "path/to/my/resource")
           .WithParameter("pagesize", 10)
           .ExpandToString();
DoCode commented 6 years ago

Thanks a lot! That's what I needed. When the resource2 is null, can a slash included inside the operator, like {/+resource2}

letsar commented 6 years ago

I'm not sure if the RFC6570 allows that, but maybe you can do something like that to handle null values:

UriTemplate.For("http://localhost/resource1{+resource2}{?q,pageindex,pagesize}")
           .WithParameter("resource2", variable?.EnsureRelativeUrl())
           .WithParameter("pagesize", 10)
           .ExpandToString();

where EnsureRelativeUrlis a method that prefixes this string with a \ char if it does not start with it.