How to get the current url with route values? - c#

I'm trying to retrieve the current request url with routes values, in order to have a return url with all needed values when reaching my controllers.
I tried HttpContext.Request.Path and HttpContext.Request.GetDisplayUrl() but it returns something like :
/Home/Products
What I actually need is to retrive the routes values to have :
/Home/Products?id=1
Is there a way to achieve that?
Thanks !

You can do this
HttpContext.Request.Path + HttpContext.Request.QueryString
Or for convenience you can create an extension method like this
public static string GetCurrentUrl(this HttpRequest httpRequest)
{
return httpRequest.Path + httpRequest.QueryString;
}
Then get current URL
var url = HttpContext.Request.GetCurrentUrl();
This link maybe helpful for you.

Related

1. Forward slash in routing parameter

I have a GET end point which will take user name as parameter. Below is the action
[Route("user/{userName}")]
public User GetUserByName([FromUri] string userName)
{
// logic here
}
This is how i make the request.
var restClient = new RestClient("uri");
var request = new RestRequest("user/" + userName);
var response = restClient.Execute(request);
It worked fine for all cases till a user with name containing forward slash came.
Eg: Akbar/Badhusha
Then the request will looks like user/Akbar/Badhusha
This causing the request to return Not Fount error
I tried to add the parameter with AddQueryParameter method. All returning Not found error.
I also tried HttpUtility.UrlEncode
Also tried replacing / with %2f
Also tried user?userName=Akbar/Badhusha
All of them failed.
Is there any way to make it work?
Try removing [FromUri] from the parameter as shown below,
[Route("user")]
public User GetUserByName(string userName)
{
// logic here
}
And the request may look like,
user?userName=Akbar/Badhush

Having trouble with IUrlHelper

I have a method like so:
[HttpPost]
public async Task<IActionResult> Index(string token)
And when i use the following line:
string url = Url.Action("Index", "Confirm", "mViH%2BZBz4l2%2Bx97rackKlFTWLVeD4xl9c%2B6ggbjbXzpAT%2BLP%2BKWvLqGymZSgV7GEPoXPSRHx6vO1ytaKPbfYrON%2BqP21EGMop3hW1%2BwoHL0Xf7bDSS5EHiqyuwNmiiJiMAYZPgr%2FCe%2FXyZFLCy%2FbfuGCOK3iawGOhdD0DyignbUC3xNybkfZkJNaXNHJlHnIv5eu8Z4wjzFkMmb1SOi5YmIzfT%2FjFovhy6fVFbDQXsc0GBzKqNsZjCudTKSPbMoRV6%2FAjw%3D%3D");
url ends up being:
"/Confirm?Length=292"
Instead of:
"/Confirm?token=mViH%2BZBz4l2%2Bx97rackKlFTWLVeD4xl9c%2B6ggbjbXzpAT%2BLP%2BKWvLqGymZSgV7GEPoXPSRHx6vO1ytaKPbfYrON%2BqP21EGMop3hW1%2BwoHL0Xf7bDSS5EHiqyuwNmiiJiMAYZPgr%2FCe%2FXyZFLCy%2FbfuGCOK3iawGOhdD0DyignbUC3xNybkfZkJNaXNHJlHnIv5eu8Z4wjzFkMmb1SOi5YmIzfT%2FjFovhy6fVFbDQXsc0GBzKqNsZjCudTKSPbMoRV6%2FAjw%3D%3D"
Does anyone know why this is the case? Nothing i've tried has worked to go around this. And if i create the link manually and use it it will work.
You need to provide route values.
An object that contains the parameters for a route. The parameters
are retrieved through reflection by examining the properties of the
object. The object is typically created by using object initializer
syntax.
string url = Url.Action("Index", "Confirm", new { token = "...." });

RedirectPermanent not redirecting to the url

I'm coding a simple URL shortener.
Everything is working, except the redirection.
Here is the code that tries to redirect:
public async Task<ActionResult> Click(string segment)
{
string referer = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : string.Empty;
Stat stat = await this._urlManager.Click(segment, referer, Request.UserHostAddress);
return this.RedirectPermanent(stat.ShortUrl.LongUrl);
}
When I input a link that is shortened, like this http://localhost:41343/5d8a2a, it redirects me to http://localhost:41343/www.google.com.br instead of www.google.com.br.
EDIT
After checking the answer, it works. Here is the final snippet of code.
if (!stat.ShortUrl.LongUrl.StartsWith("http://") && !stat.ShortUrl.LongUrl.StartsWith("https://"))
return this.RedirectPermanent("http://" + stat.ShortUrl.LongUrl);
else
return this.RedirectPermanent(stat.ShortUrl.LongUrl);
Thanks!
Instead of RedirectPermanent() try using Redirect() like below. The specified URL has to be a absolute URL else it will try to redirect to within your application.
You can check for existence of http:// and add it accordingly
if(!stat.ShortUrl.LongUrl.Contains("http://"))
return Redirect("http://" + stat.ShortUrl.LongUrl);
(OR)
Use StartsWith() string function
if(!stat.ShortUrl.LongUrl.StartsWith()("http://"))
return Redirect("http://" + stat.ShortUrl.LongUrl);

Get site url on mvc

I want to write a little helper function that returns the site url.
Coming from PHP and Codeigniter, I'm very upset that I can't get it to work the way I want.
Here's what I'm trying:
#{
var urlHelper = new UrlHelper(Html.ViewContext.RequestContext);
var baseurl = urlHelper.Content("~");
}
<script>
function base_url(url) {
url = url || "";
return '#baseurl' + url;
}
</script>
I want to return the base url of my application, so I can make ajax calls without worrying about paths. Here's how I intend to use it:
// Development
base_url(); // http://localhost:50024
// Production
base_url("Custom/Path"); // http://site.com/Custom/Path
How can I do something like that?
EDIT
I want absolute paths because I have abstracted js objects that makes my ajax calls.
So suppose I have:
function MyController() {
// ... js code
return $resource('../MyController/:id');
}
// then
var my_ctrl = MyController();
my_ctrl.id = 1;
my_ctrl.get(); // GET: ../MyController/1
This works when my route is http://localhost:8080/MyController/Edit but will fail when is http://localhost:8080/MyController .
I managed to do it like this:
#{
var url = Request.Url;
var baseurl = url.GetLeftPart(UriPartial.Authority);
}
Thank you all!
Are you aware of #Url.Action("actionname") and #Url.RouteUrl("routename") ?
Both of these should do what you're describing.
Instead of manually creating your URL's, you can use #Url.Action() to construct your URLs.
<p>#Url.Action("Index", "Home")</p>
/Home/Index
<p>#Url.Action("Edit", "Person", new { id = 1 })</p>
/Person/Edit/1
<p>#Url.Action("Search", "Book", new { title = "Gone With The Wind" })</p>
/Book/Search?title="Gone+With+The+Wind"
Now the absolute best reason to go with this option is that #Url.Action automatically applies any vanity URL routes you have defined in your Global.asax file. DRY as the sub-saharan desert! :)
In your case, your can create a 'custom path' in two ways.
Option A)
<p>#Url.Action("Path", "Custom")</p>
/Custom/Path
Option B)
You can create a route using the Global.asax file. So your controller/action combo can be anything you want, and you can create a custom vanity route url - regardless of the controller/action combo.

url does not decode properly with request[] in C#

I have an object like this:
public class adapterContext {
public HttpRequest Request;
}
adapterContext ac = new adapterContext();
ac.Response = context.Response;
I pass this object to my functions and use ac.Request[""] to get my url variables. However this somehow does not translate national/special characters correct. When I use f.ex this as part of the URL: prospectName=Tester+%e6+%f8+%e5
I get "Tester ? ? ?"
From the debugger I get: ac.Request["prospectName"][7] 65533 '�' char
Anyone have any idea how I should fix this?
there's a nice function, you should take care of: HttpUtility.UrlDecode(string, Encoding) ...
otherwise you need to adjust the globalization setting in your web.config (requestEncoding, responseEncoding ...)

Categories

Resources