replace partial url with another url in c#? - c#

I have URL need to replace partial url with another url.
Original Url
http://oldurl/dept/it/Lists/Contract Management System/DispForm.aspx?ID=4
I want to replace just http://oldurl (only) with http://www.newurl.com. Rest of the url will change dynamically.

Request.oldURL.GetLeftPart(UriPartial.Authority) will return your base url string which is http://oldurl
string oldURL = "http://oldurl/bs/blabla";
string newURL = oldURL.Replace(Request.oldURL.GetLeftPart(UriPartial.Authority), "http://www.newurl.com");
See more: https://msdn.microsoft.com/en-us/library/system.uri.getleftpart(v=vs.110).aspx

Related

How can I send URL parameter in ASP.NET Core Web API parameters

I wrote this code in a C# ASP.NET Core Web API project:
[HttpGet]
[Route("GetShortURL/{_url}/{tokenPass}")]
[ApiExplorerSettings(GroupName = "ShortURL")]
public ActionResult<ServiceResult<string>> GetShortURL(string _url, string tokenPass)
When I enter this parameter as _url, I get an error:
Error: Not Found
https://github.com/VahidN/DNTPersianUtils.Core
http://...//GetShortURL/https%3A%2F%2Fgithub.com%2FVahidN%2FDNTPersianUtils.Core/TokenPass
How can I call this API with the first Web URL parameter?
when i change the [Route("GetShortURL/{_url}/{tokenPass}")] to [Route("GetShortURL")] the problem was solved but i want to send query by / not by ?
for example, i want to call API like this :
1- http://..../GetShortURL/_UrlParam/_TokenPassParam
not like below :
2- http://..../GetShortURL?_url=_urlParam&tokenPass=_TokenPassParam
the second way works fine but I want first way to work correctly when i pass an URL like this
https%3A%2F%2Fgithub.com%2FVahidN%2FDNTPersianUtils.Core
can anyone help me?
First approach:
Pass the params you want as query string and then change the method like below:
[HttpGet("GetShortURL")]
[ApiExplorerSettings(GroupName = "ShortURL")]
public ActionResult<ServiceResult<string>> GetShortURL(string _url, string tokenPass)
Then For extracting the different parts of the url (protocol, domain name, path and query string), use the code below (path is an array separated by slash):
try
{
var decodedUrl = System.Web.HttpUtility.UrlDecode(_url);
Uri uri = new Uri(decodedUrl);
var scheme = uri.Scheme;
var host = uri.Host;
var absolutePathSeperatedBySlash = uri.AbsolutePath.Split('/').Skip(1).ToList();
var query = uri.Query;
// rest of the code ...
}
catch (Exception ex)
{
//...
}
Second approach:
If you want it to be sent as a url parameter, first you have to encode the value of _url with encodeURIComponent() in javascript, to make sure that some special characters like , / ? : # & = + $ # are changed.
Then:
[HttpGet("GetShortURL/{_url}/{tokenPass}")]
[ApiExplorerSettings(GroupName = "ShortURL")]
public ActionResult<ServiceResult<string>> GetShortURL(string _url, string tokenPass)
The rest is just like the method body of the first approach.
With the following url
http://...//GetShortURL/https%3A%2F%2Fgithub.com%2FVahidN%2FDNTPersianUtils.Core/TokenPass
The value of _url will be:
If you want to convert it to a correct url,you needs to replace %2F with / in GetShortURL:
var url = _url.Replace("%2F","/");
just make parameters to be optional
[HttpGet("GetShortURL/{_url?}/{tokenPass?}")]
public ActionResult<ServiceResult<string>> GetShortURL(string _url, string tokenPass)
in this case you can call the action without any parameters, with one parameter or with two parameters

AbsoluteUri need to return correct path

Using method bellow in my MVC view I am getting URL like "localhost:54871/Home/Index" but I don't want "Index" on last. It should be only "localhost:54871/Home". How should I implement this?
#(Request.Url.AbsoluteUri)
Thank you for your help!
While using Request.Url.AbsoluteUri the url changes based on the user's current page.
If user visits http://localhost:0000/Home/ then AbsoluteUri is http://localhost:0000/Home/
If user visits http://localhost:0000/Home/Index then AbsoluteUri is http://localhost:0000/Home/Index
In MVC url generation is based on the route definition defined in RouteConfig.cs file.
You can define route just for controller name, check this and this
Also there is another solution as below:
#{
Uri uriAddress = new Uri(Request.Url.AbsoluteUri);
string urlLeftPart = uriAddress.GetLeftPart(UriPartial.Authority);
string controllerName = HttpContext.Current.Request.RequestContext.RouteData.
Values["controller"].ToString();
string finalURL = urlLeftPart + "/" + controllerName;
}
Url Without Action Name
References
1.
2.
You can try the below one.
For Example if the url with parameters are like below
http://localhost:61221/Websitetest/Default1.aspx?QueryString1=1&QueryString2=2
Then by using the below code you can get the results
HttpContext.Current.Request.Url.Host
HttpContext.Current.Request.Url.Authority
HttpContext.Current.Request.Url.Port
HttpContext.Current.Request.Url.AbsolutePath
HttpContext.Current.Request.ApplicationPath
HttpContext.Current.Request.Url.AbsoluteUri
HttpContext.Current.Request.Url.PathAndQuery
will provide the output like below
OUTPUT
localhost
localhost:61221
61221
/Websitetest/Default1.aspx
/Websitetest
http://localhost:61221/Websitetest/Default1.aspx?QueryString1=1&QueryString1=2
/Websitetest/Default1.aspx?QueryString1=1&QueryString2=2

asp:hyperlink navigate url adding relative path to the url

I have a Asp:Hyperlink in aspx page and i am setting the text and navigation url dynamically but when page renders it adds the relative path of my website in the rendered href. i dont know why?
ASPX
<asp:HyperLink runat="server" ID="charityNameText"></asp:HyperLink>
CODE-BEHIND (Page Load Event)
//Getting data from database
charityNameText.Text = entryDetails.RegisteredCharityName;
charityNameText.NavigateUrl = "www.facebook.com";
charityNameText.Target = "_blank";
Rendered HTML
<a id="ctl00_PageContent_CompetitionsEntries_ctl06_charityNameText" href="../../ConLib/Custom/www.facebook.com" target="_blank">save the childrens</a>
../../ConLib/Custom/ is the path where this file is located.
Plase help
There are different solutions for your case.
My best approach would be using the System.UriBuilder class.
String myUrl = "www.facebook.com";
UriBuilder builder = new UriBuilder(myUrl);
charityNameText.NavigateUrl = builder.Uri.AbsoluteUri;
The UriBuilder adds the protocol (HTTP) in your case to the URL you are loading and initializes an instance of the Uri class with the complete URL. Use the AbsoluteUri property.
For more complex cases you can use Regex :
String myUrl = "www.facebook.com";
System.Text.RegularExpressions.Regex url = new System.Text.RegularExpressions.Regex(#"/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.MatchCollection matches = url.Matches(myUrl);
foreach (System.Text.RegularExpressions.Match match in matches)
{
string matchedUrl = match.Groups["url"].Value;
Uri uri = new UriBuilder(matchedUrl).Uri;
myUrl = myUrl.Replace(matchedUrl, uri.AbsoluteUri);
}
You have to add the protocol to the beginning of the URL:
http://wwww.facebook.com
I think you should use http://www.facebook.com
Hope that helps

Get anything after first slash in URL

I can get my browser url using : string url = HttpContext.Current.Request.Url.AbsoluteUri;
But say if I have a url as below :
http://www.test.com/MyDirectory/AnotherDir/testpage.aspx
How would I get the "MyDirectory" part of it, is there a utility in .NET to get this or do I need string manipulation ?
If I do string manipulation and say anything after first instance of "/" then wouldnt it return the slash after http:? It would work if my url was www.test.com/MyDirectory/AnotherDir/testpage.aspx
Can someone please help
Instantiate a Uri instance from your url:
Uri myUri = new Uri("http://www.test.com/MyDirectory/AnotherDir/testpage.aspx");
You can then get the path segments into a string array using:
string[] segments = myUri.Segments
Your first "MyDirectory" folder will be at:
string myFolderName = segments[0];
You can get this by PathAndQuery property of Url
var path = HttpContext.Current.Request.Url.PathAndQuery;
it will return /MyDirectory/AnotherDir/testpage.aspx
Uri uriAddr = new Uri("http://www.test.com/MyDirectory/AnotherDir/testpage.aspx");
var firstSegment= uriAddress.Segments.Where(seg => seg != "/").First();

I want to get part of the url in ASP.NET MVC

http://localhost:6223/RssFeed/RssFeedsLang?lang=Dari&cat=News
How can I get the http://localhost:6223/ of the url? Basically I want to discard /RssFeed/RssFeedsLang?lang=Dari&cat=News in the url. How can I do that?
Use this:
string urlBase = Request.Url.GetLeftPart( UriPartial.Authority ) + Request.ApplicationPath;

Categories