Reputation: 3133
I have a Uri with a URL in the format: /Review/{product name}/{id}
I'd like to update segment product name like:
uri.Segments[2] = product.UrlFriendlyProductName;
when I execute the above code, the Uri doesn't update. Any Suggestions?
Upvotes: 3
Views: 2605
Reputation: 5884
The UriTemplate
class could be useful for you, but it is not available in .NET Core.
Try maybe Tavis.UriTemplates library.
Upvotes: 0
Reputation: 101643
Uri
class is immutable in a sense that you cannot modify it via public interface. Segments
basically just splits Path
by '/' and returns that. To edit Uri
you can use UriBuilder
class (which still doesn't modify original, but creates a modified copy). But it doesn't contain convenient Segments
property, so you have to split yourself. For example:
var url = new Uri("http://something/Review/name/1");
var builder = new UriBuilder(url);
// extract segments from path
var segments = builder.Path.Split('/');
// modify
segments[2] = "bla";
// combine back
builder.Path = String.Join('/', segments);
// modified uri
var result = builder.Uri;
Upvotes: 5