简体   繁体   中英

Get the last path of URL

I'm using the following code which is working just fine for most of the services but some time in the URL last I got User;v=2;mp and I need to get just User ,how should I handle it? I need some general solution since I guess in some other URL I can get different spacial charters

if the URL

https://ldmrrt.ct/odata/GBSRM/User;v=2;mp
string serviceName = _uri.Segments.LastOrDefault();

if the URL is https://ldmrrt.ct/odata/GBSRM/User its working fine...

Just replace:

string serviceName = _uri.Segments.LastOrDefault();

With:

string serviceName = _uri.Segments.LastOrDefault().Split(new[]{';'}).First();

If you need something more flexible, where you can specify what characters to include or skip, you could do something like this (slightly messy, you should probably extract parts of this as separate variables, etc):

// Note the _ and - characters in this example:
Uri _uri = new Uri("https://ldmrrt.ct/odata/GBSRM/User_ex1-ex2;v=2;mp");

// This will return a string: "User_ex1-ex2"
string serviceName =
        new string(_uri.Segments
                          .LastOrDefault()
                          .TakeWhile(c => Char.IsLetterOrDigit(c)
                                          || (new char[]{'_', '-'}).Contains(c))
                          .ToArray());

Update, in response to what I understand to be a question below :) :

You could just use a String.Replace() for that, or you could use filtering by doing something like this:

// Will return: "Userexex2v=2mp"
string serviceName = 
             new string(_uri.Segments
                            .LastOrDefault()       
                            .Where(c => 
                                    !Char.IsPunctuation(c) // Ignore punctuation
                                    // ..and ignore any "_" or "-":
                                    && !(new char[]{'_', '-'}).Contains(c)) 
                             .ToArray());

If you use this in production, mind you, be sure to clean it up a little, eg by splitting into several variables, and defining your char[]-array prior to usage.

In your case you can try to split a "User;v=2;mp" string.

string [] split = words.Split(new Char [] { ';' });

Returns a string array that contains the substrings in this instance that are delimited by elements of a specified Unicode character array.

split.First();

or:

split[0];

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