Hide parameters from #Url.Action - c#

I have this code
<a href="#Url.Action(" Edicao ", "EdicaoListaVerificacao ", new { idFormulario = m.Id })" title="Editar" class="glyphicon glyphicon-pencil" aria-hidden="true" />
Where 'Edit' is my action and 'FunctionEdit' is my Controller. My action needs a parameter and I passed it building a 'instance'. How the property needs. The problem is that the URL can be altered and the user can access things that they can't.

You can never hide your URLs - nor should you. You should verify, instead, inside the Edicao action method that the user has permission to view the Formulario with the specified Id.
In all web applications, you have to assume that the URLs users try to retrieve can be absolutely anything - and that some users will attempt to edit URLs to get at hidden content. ASP.NET has built-in authentication and authorization mechanisms that you should use.
If you're just looking for a simple way to make a URL that's impossible to guess, without forcing users to log on, you have to use something more complicated than a numeric ID, like a GUID.
And if at any point you are tempted by roll-your-own solutions such as URL referrer checking or verifying cookies, remember that easier-to-use solutions are most likely built into ASP.NET already.

That's it! Thank you, guys. I found a way to implement a check in my action. With Request.UrlReferrer.
public ActionResult Edicao(int idFormulario)
{
Uri url = Request.UrlReferrer;
if (url != null)
{
DO ALL THINGS YOU HAVE TO
}
else
{
RETURN TO INDEX
}
}
The Request.UrlReferrer returns me the URL if it comes from my request. If not returns null. Than I just build an if block ;). Thank you guys!

Related

Updating the displayed URL in the browser using .NET Core

So, I have a certain webpage (view) that I have created. I have a requirement where I need to update the displayed URL in the browser's to show a different path to this page and update the querystring.
Update: I don't want to actually redirect the page, this is merely a cosmetic update. To make the URL appear differently that what it was. It's a requirement our customer support team wanted. :p
Ex.
https://www.myserver.com/error/
I need to update the path in the URL depending on the type of error, like so:
https://www.myserver.com/#/order-completed?var=someguid
My error page handles various situations you see.
I know this is easily done in JS, but I want to be able to do this from my error page Controller.
Could someone lend a hand? I'd super appreciate it!
I think "update the path" means you simply have to redirect the browser to that url. If you are using ASP.NET MVC, you can use the Redirect controller method like this:
return Redirect("https://www.myserver.com/#/order-completed?var=someguid");
So, I went the way of JS afterall. I call it from window.onload in the View.
var fromController = '#ViewData["NewURL"]';
histoy.pushState(null, '', fromController);
In the Controller, in the Index() action
ViewData["NewURL"] = #"/myURL/myview?user=2342434";
return View();

Routing: how do I redirect to a url when a parameter is missing?

I have routes like this:
example.com/{category}/articles.
There isn't a route for
example.com/{category}
example.com/
I want to redirect all that traffic to
example.com/{category}/articles with a default value.
I've read that I can use default values with a RouteValueDictionary:
routes.MapPageRoute("ArticlesAll", "{category}/articles/", "~/ArticlesPage.aspx", false, new RouteValueDictionary { { "category", "cats" } });
But that doesn't do any redirecting.
Would I need another route to forward to the one above or is there a more efficient way of doing this?
What you are asking is a bit unclear, but let me offer what I usually do.
If you are trying to make it so that two similar links can be written, for example www.example.com/read/penguin/article/ and www.example.com/read/panda/article. I would just write the whole string / URL with a variable in the middle:
private string destination = "penguin";
private string url = "www.example.com/read/" + destination + "/article/";
void Test () {
destination = "lion";
text.URL = url;
}
Sorry, I may have made gramatical mistakes in my code, but I hope you get the point. I may have completely misunderstood you though, so clarification would be appreciated.
You can setup these two routes:
routes.MapPageRoute("ArticlesAll", "{category}/articles/{*value}", "~/ArticlesPage.aspx");
routes.MapPageRoute("CatchAll", "{*value}", "~/ArticlesPage.aspx");
to catch anything and redirect to your desired page. I just assumed where you want to lead your users, change the aspx part as needed. Keep in mind that you can use {value} to access the whatever the user wrote.
For example if they wanted to navigate to dogs and you wanted to redirect to dogs/articles/ArticlesPage.aspx, you should use:
routes.MapPageRoute("CatchAll", "{*value}", "~/{value}/articles/ArticlesPage.aspx");
EDIT
If you want to actually redirect to the new URL and not just serve up the right page, you can use the CatchAll route to redirect to a page (say Redirect.aspx) that's sole purpose is to parse data from the RouteData object, construct the new URL and Redirect.

Query String Parameter Being Lost on Request

i'm developing an MVC 4 web application.
I'm trying to make an url that changes in an authorized/unauthorized context.
I'm generating the following url for unauthorized user:
http://localhost/vendas-web/Login?ReturnUrl=%2Fvendas-web%2FClienteNovo%2FIndex%299999
The first time I've tested, it worked just fine.
But.. the second time I've tried, the query string got lost.. and the url turned into:
http://localhost/vendas-web/Login
When i test it against chrome on anonymous tab, it works FINE.
When i change the value of the last parameter, it works FINE.
There's some sort of cache related to this ?
What i'm doing wrong ?
Soo, my question is:
How do i keep my full url in any scenario ??
Ty
There's really not enough information here, but what you're likely talking about is that the first time a user needs to be authorized, they are automatically redirected to the first URL, which includes the ReturnUrl bit. That's built into the framework to allow the user to be redirected back to that URL after logging in. However, if you need to persist this past that initial first redirect to the login page, that's on you. Any links must manually add the query string param:
#Url.Action("SomeAction", new { ReturnUrl = Request["ReturnUrl"] })
And any forms must include it as a hidden input:
#Html.Hidden("ReturnUrl", Request["ReturnUrl"])
Otherwise, yes, it will be lost, because the literal URL you're now requesting doesn't include it. It's not just magically appended.
My problem was cache...
I've used this annotation to avoid using cache by application.
[OutputCache(NoStore = true, Duration = 0)]

How do I redirect to my parent action in MVC site?

I have been looking at several pages on here already such as:
How do I redirect to the previous action in ASP.NET MVC?
How can I redirect my action to the root of the web site?
Along with several hours of searching google.
No where seems to have an answer to my problem and I am sure it should be possible within MVC somehow hence the reason I am now here to ask the question.
So the problem I am facing is that I want to allow the user to change the language of the page by choosing a new language from a drop down menu which is in its own partial view hence the problem, I need to redirect to the parent action and not the child. This all works fine as long as i send the user back to the root of the site. Using the following code:
[HttpPost]
public ActionResult RegionSelect(RegionSelectionModel model)
{
var currentUser = Session.GetCurrentUser();
var currentDbUser = Session.GetUserEntity(_dataAccessLayer);
if (!ModelState.IsValid)
{
model.AvailableRegions = CacheHelpers.GetAvailableRegions<RegionView>(_dataAccessLayer, _cache).ToList();
return PartialView("_RegionSelect", model);
}
var selectedRegion = UsersControllerHelpers.SetSelectedRegion(model, _dataAccessLayer, _cache, _website.Client);
var uri = model.OriginalUrl;
var routeInfo = new RouteHelpers(uri, HttpContext.Request.ApplicationPath);
// Route Data
var routeData = routeInfo.RouteData;
routeData.Values.Remove("language");
var defaultClientLanguageCode = _website.Client.LanguagesSupported.FirstOrDefault().Code;
if (currentDbUser.Language.CountryCode != selectedRegion.PrimaryLanguage.CountryCode)
{
//TODO: Decide where to redirect or whether to refresh the whole page...
if ((defaultClientLanguageCode == selectedRegion.PrimaryLanguage.CountryCode) || (model.SelectedRegionId == 0))
{
UsersControllerHelpers.UpdateUsersRegions(currentUser, selectedRegion, _website.Client, _cache, _dataAccessLayer,
Session);
return RedirectToRoute(routeData.Values);
}
routeData.Values.Add("language",selectedRegion.PrimaryLanguage.CountryCode);
return RedirectToRoute(routeData.Values);
}
return RedirectToRoute(routeData.Values);
}
Two of my return statements return to the root page and one returns to the root but with a language so it would be "http://mysite/en-En/" but what if the user is on a page other than the root site? I want to somehow redirect them back to this same action but with the correct language string at the start.
How can i do this?
I have thought of several "hacky" ways of doing this, such as splitting the URL and swapping the language codes over. But ideally I am looking to do this as clean as possible.
Can anyone give me any idea's? Or is it just not possible?
It seems like it should be really simple but apparently not.
Thanks in advance for any help that you can provide.
EDITED
Added new code that is using code from suggested answer below.
I am now having two new problems.
I am getting this error message, if there are any things in the URL such as ?page=1:
A potentially dangerous Request.Path value was detected from the client (?)
If i try and remove the language completely using .Remove(). It removes it fine but when i try and redirect to the page in the default language it adds language?=language to the end of the URI.
Any ideas how i can resolve these two issues?
This option is definitely my answer. Leave me a comment if you need me to drop some code, and I can do that, but the examples on the linked website should get you started.
Use this method to change Request.UrlReferrer into Route data, then merge your language into that, then do a RedirectToRoute with the modified Route data.
Just use RouteData.Values.Add, RouteData.Values.Remove, and RouteData.values["whatever"], then pass that modified RouteData.Values object to RedirectToRoute()

How to make a route unique

I use asp.net 4 c# and routing.
I have two routes, as you can see I pass to arguments for each route {ContentId} and {TitleUrl}, please pay attention at the first part article/ and blog/.
Here an example of correct resulted
mysite.com/article/150/my-special-article
mysite.com/blog/25/my-special-blogpost
If a User try to manipulate the URL changing article/ and blog/ section, the route continue to display the content.
mysite.com/article/150/my-special-article // same page
mysite.com/somtheingelsehere/150/my-special-article // same page
My web site at the moment continue to display the content, but I need some sort of validation and make sure that my requested URL is as specified in the route or I would show a 404 page.
Any idea how could solve it? (I hope guys I was able to explain in properly, if you need more clarificaiton please let me know). Thanks!
routes.MapPageRoute("ArticleDetails", "article/{ContentId}/{TitleUrl}", "~/ContentDetails.aspx");
routes.MapPageRoute("BlogPostDetails", "blog/{ContentId}/{TitleUrl}", "~/ContentDetails.aspx");
My suggestion is either use different pages for articles and blog posts, or in ContentDetails.aspx check for the correct URL accordingly.
if (Request.Url.PathAndQuery.StartsWith("/blog/") && postType = "blog") ...

Categories