Query String Parameter Being Lost on Request - c#

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)]

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();

MVC Redirect to another page

I have a controller which processes an uploaded file.
In that controller, I return the user to a SharePoint list depending on the successful parsing of that file. I am able to enter a direct URL, but I am opening this page in a form so I need to change the window.top.location instead of just window.location. I tried doing this a few ways such as returning a JavaScript result, but I received some browser warning messages I'd like to avoid.
I ended up making a partial razor view which grabs a parameter from the query string in order to determine which list it should go to. The function works fine, but the page is seemingly inactive when I return it using:
return Redirect("~/Parsing/ParsingRedirector?List=MasterDealer");
My page exists in the folder, but I get an error stating "The resource cannot be found. "
Any reason why that's happening? I admittedly don't have a full understanding of MVC or even close to it at this point.
Try this:
return RedirectToAction("ParsingRedirector", "Parsing", new { List = "MasterDealer"});
This may be of help:
http://www.dotnet-tricks.com/Tutorial/mvc/4XDc110313-return-View()-vs-return-RedirectToAction()-vs-return-Redirect()-vs-return-RedirectToRoute().html
Keep in mind that, per that article, in the case of Redirect "you have to specify the full URL to redirect."

login to ajax web page from c# code

i'm trying to log in a site with username + password through a c# code.
i found out that it uses Ajax to authenticate...
how should i implement such login ?
the elements in the web page doesn't seem to have an "id"...
i tried to implement it using HtmlAgilityPack but i don't think this is the correct direction...
i can't simulate a click button since i don't find "id" for the button.
if (tableNode.Attributes["class"].Value == "loginTable")
{
var userInputNode =
tableNode.SelectSingleNode("//input[#data-logon-popup-form-user-name-input='true']");
var passwordInputNode =
tableNode.SelectSingleNode("//input[#data-logon-popup-form-password-input='true']");
userInputNode.SetAttributeValue("value", "myemail#gmail.com");
passwordInputNode.SetAttributeValue("value", "mypassword");
var loginButton = tableNode.SelectSingleNode("//div[#data-logon-popup-form-submit-btn='true']");
}
This question is quite broad but I'll help you in the general direction:
Use Chrome DevTools (F12) => Network tab => Check the "Preserve Log". An alternative could be Fiddler2
Login manually and look at the request the AJAX sends. Save the endpoint (the URL) and save the Body of the request (the Json data that's in the request with username and password)
Do the post directly in your C# code and forget about HtmlAgilityPack unless you need to actually get some dynamic data from the page, but that's rarely the case
Login with something like this code snippet: POSTing JSON to URL via WebClient in C#
Now you're logged in. You usually receive some data from the server when you're logging in, so save it and use it for whatever you want to do next. I'm guessing it might have some SessionId or some authentication token that your future requests will need as a parameter to prove that you're actually logged in.

How to retrieve site root url?

I need to get the url of the site so that I render a user control on only the main page. I need to check for http://foo.com, http://www.foo.com, and foo.com. I am a bit stumped as to how check for all 3. I tried the following which does not work.
string domainName = Request.Url.Host.ToString();
if (domainName == "http://nomorecocktails.com" | Request.Url.Host.Contains("default.aspx"))
{ //code to push user control to page
Also tried
var url = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + "/";
Any thoughts?
You need to check if the Request.Path property is equal to / or /Default.aspx or whatever your "main page" is. The domain name is completely irrelevant. What if I accessed your site via http://192.56.17.205/, and similarly, what if your server switched IP addresses? Your domain check would fail.
If you utilize the QueryString to display different content, you'll also need to check Request.QueryString.
Documentation for Request.Path:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.path.aspx
Documentation for Request.QueryString:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.querystring.aspx
If you need the user control to only appear on the main page (I'm assuming you mean home page), then add the code to call the user control to the code behind of that file.
If this code is stored in the master page, then you can reference it like:
Master.FindControl("UserControlID");
If you are only using the one web form (ie. just Default.aspx), then you can check that no relevant query strings are included in the URL, and display only if this is the case:
if (Request.QueryString["q"] == null){
//user control code
}
However if you are using this technique then I would recommend using multiple web forms using master pages in the future to structure your application better.
The ASP.NET website has some good tutorials on how to do this:
http://www.asp.net/web-forms/tutorials/master-pages

How to encode the redirect_uri for facebook login

I'm trying to build a login link for facebook and I'm I'm getting errors only in some cases. I'm trying to specify a a querystring parameter in redirect_uri token so that I can redirect them back to a specific area of my site after logging in. Here's what works and what doesn't work.
&redirect_uri=http://mydomain.com/login?returnUrl=returnUrl - works
&redirect_uri=http://mydomain.com/login?returnurl=/return/url -doesn't work
&redirect_uri=http%3a%2f%2fmyagentcheckin.com%2flogin%3freturnUrl%3d%2freturn%2furl -doesn't work
It seems that the / in the querystring are causing it to fail. Facebook returns an error when I try it. Anyone know of a way around this?
Instead of including the returnUrl parameter as part of your redirect_uri value, use the state parameter to store this data.
For instance,
https://graph.facebook.com/oauth/authorize?type=web_server&client_id={appid}&redirect_uri=http://www.yoursite.com/oauth/handshake&state=/requested/page
I have experienced something similar, especially with multiple redirects as above.
My solution is to put the returnUrl into the user's session (or perhaps a cookie), so I don't have to wrestle with double-encoding. For the redirect_url, just omit the querystring.
Try using this API that put together. It will remove the hassle of this for you.
No url encoding necessary.
Sample Authentication
Imports Branches.FBAPI
...
Dim SI As New SessionInfo("[application_id]","applicaiton_secret")
SI.AuthenticateUser("http://[my url]", New SessionInfo.PermissionsEnum(){SessionInfo.PermissionsEnum.email, SessionInfo.PermissionsEnum.read_stream}))
Read the response from the URL you provided above from that page.
Dim FSR = FS.ReadFacebooAuthResponse
When I tried what you do, I got a redirect callback something like this.
http://mydomain.com/login?returnurl=%2Freturn%2Furl&code=...
And I decode the "returnurl" value.
Then it worked fine for me.

Categories