Parsing and URL string coming from database in MVC C#.

Here in the code splittting the string and find if its legnth is greater than 2 then gets the controller and action name and redirects to right action method. Is there any better way to parse the db string ?

String abc = "/A/B/C.asp?Target=Z"; // getting this mvc string url from db
var target = abc.Split('/');
if (target.Length < 2) throw new Exception("unable to find link - Link: " + abc);
var controller = target[target.Length - 2];
var action = target[target.Length - 1];
return RedirectToAction(action, controller, menuModel);
else
//do something else

Open in new window

satmishaAsked:
Who is Participating?
 
Fernando SotoRetiredCommented:
Hi satmisha;

How about using a regular expression to parse the string. Something like this.
using System.Text.RegularExpressions;

// Regex pattern to match the input with
var pattern = "/.+/(?<Controller>.+)/(?<Action>.+)";
// The data from the database
var input = "/A/B/C.asp?Target=Z";
// Find the controller and action
Match results = Regex.Match(input, pattern);
// If a match was found
if(results.Success)
{
    // Access the Controller and Action values
    Console.WriteLine("The Controller : {0}\nThe Action : {1}", results.Groups["Controller"], results.Groups["Action"]);
}
else
{
    // If not found throw an exception
    throw new Exception("unable to find link - Link: " + input);
}

Open in new window

1
 
MishaProgrammerCommented:
Why not? It not bad method, if we speak only about parse string. May be you can optimization information, which you store in database,.
0
 
Miguel OzSoftware EngineerCommented:
I agree with Misha, rather than saving a url just save the controller and action to the database , thus no need to do extra parsing.
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
satmishaAuthor Commented:
thanx experts.

I am actually getting the url from db as I mentioned and something it redirects to mvc controller and action and sometimes to .aspx or .asp pages.


String abc = "/A/B/C.asp?Target=Z"; // getting this mvc string url from db.
0
 
Fernando SotoRetiredCommented:
Hi satmisha;

Please try my posted solution above, it will do what you need.
0
 
satmishaAuthor Commented:
Thanks Fernando Soto
0
 
satmishaAuthor Commented:
Thanks Pal.
0
 
Fernando SotoRetiredCommented:
Not a problem satmisha, glad to help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.