Getting the url of the current request - c#

I have a page for registering students and an email activation link is sent after submitting records. I have included the link for activation but it gets the whole url and includes it in the email. Can someone show how to solve the issue as currently it sends the whole page url in the email? Here is a sample of what is send to email:
localhost:89192/Staff/Register.aspx?rwndrnd=0.6363636646446373333CompleteRegistration.aspx?id=8901b88k1-81fa-8u10-m96e-892f6aea6710
Below is how am getting the current url
activationUrl = HttpContext.Current.Request.Url.Host+""+"://CompleteAccount.aspx?id=" + id.ToString();

Simply use
activationUrl = Request.Url.AbsoluteUri
Also, Request.Url.ToString() returns the full url (including querystring)

Related

how to add additional query after link path

I am sending link to email address for password reset functionality and after sometime i want this link to expire. for that i have created a token(which is encrytped using a key) and expire-date and i want to put these as query in my email link but i don't know to do it.
this is how i use token class in forgotPassword Post method.
var tokenModel = new LinkExpire();
tokenModel.ExpiresOn = DateTime.Now.AddSeconds(10);
tokenModel.CreateToken = TokenHelperMethods.GetToken(tokenModel);
this is my link code.
string resetCode = Guid.NewGuid().ToString();
var varifyUrl = "/E_HealthCare_Web/Account/ResetPassword/" + resetCode;
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, varifyUrl);
and in my email body i am sending link like this
"<br/> <br/> <a href = '" + link +"&expire="+tokenModel.ExpiresOn+"&token="+tokenModel.CreateToken+"'>Reset link</a> <br/><br/>" +
which does not to work as expected. anyone can help me achieve this, also i am not using core, only mvc5.
Edit this is my controller where i am recieving link values
public ActionResult ResetPassword(string id, DateTime expire, string token)
while clicking on link gives A potentially dangerous Request.Path value was detected from the client (&) error.
Here is my suggestion, instead of adding expiration token query parameters with URL manage this at your method action level i.e.
You already have the information that which login is going to this URL. All you have to do is that before sending this URL via email, make a separate temp table that will have user ID, reset password URL path, created date/time column (this column will mange the data/time when you send the URL to the user for password reset) and active/Iactive status column.
Now at code level when this particular URL is hit by user, first get the active row only entry against this URL & user ID and get the created date/time column value.
Check the difference between the active created date/time column and current date/time.
if difference between two dates is more than 24hr send expiration response otherwise change the password.
Mark that entry as inactive.
Know that against each user the active entry in this new table exist only when user request's password reset, otherwise all existing entries are marked as inactive.
You can delete instead of active/inactive as well. this is temp table.

How to get response from IPN cryptocurrencies

We're trying to receive payment with cryptocurrencies using coinpayment IPN. We are able to create a request and able to do a payment. However, not able to get success or failure response while user come back to the seller side.
Here is how payment request created:
public ActionResult IPN()
{
var uri = new UriBuilder("https://www.coinpayments.net/index.php");
uri.SetQueryParam("cmd", "_pay_auto");
uri.SetQueryParam("merchant", "merchant_key");
uri.SetQueryParam("allow_extra", "0");
uri.SetQueryParam("currency", "USD");
uri.SetQueryParam("reset", "1");
uri.SetQueryParam("success_url", "http://localhost:49725/home/SuccessResponse"); //todo: redirect to confirm success page
uri.SetQueryParam("key", "wc_order_5b7b84b91a882");
uri.SetQueryParam("cancel_url", "http://localhost:49725/home/FailiureResponse");
uri.SetQueryParam("order_id", "36");
uri.SetQueryParam("invoice", "PREFIX-36");
uri.SetQueryParam("ipn_url", "http://localhost:49725/?wc-api=WC_Gateway_Coinpayments");
uri.SetQueryParam("first_name", "John");
uri.SetQueryParam("last_name", "Smith");
uri.SetQueryParam("email", "a#a.com");
uri.SetQueryParam("want_shipping", "1");
uri.SetQueryParam("address1", "228 Park Ave S&address2");
uri.SetQueryParam("city", "New York");
uri.SetQueryParam("state", "NY");
uri.SetQueryParam("zip", "10003-1502");
uri.SetQueryParam("country", "US");
uri.SetQueryParam("item_name", "Order 33");
uri.SetQueryParam("quantity", "1");
uri.SetQueryParam("amountf", "100.00000000");
uri.SetQueryParam("shippingf", "0.00000000");
return Redirect(uri.ToString());
}
This will be redirected to the coinpayment site, once payment done, it is showing the following screen.
And trying to get data when user click on back to seller's site, I have tried to get data using Request.Form, but not getting any value in form.
The same thing, working with this woocommerce code, but I have no idea of PHP and how they are dealing with it.
Any thought to get IPN response?
Note: there is no development documentation or sample code available for IPN in .NET
Edit
I'm trying to get value from IPN success
Public ActionResult SuccessResponse()
{
var ipn_version = Request.Form["ipn_version"];
var ipn_id = Request.Form["ipn_id"];
var ipn_mode = Request.Form["ipn_mode"];
var merchant = Request.Form["merchant"];
var txn_id = Request.Form["txn_id"];
var status = Request.Form["status"];
return Content(status);
}
You cannot use localhost for a IPN callback. You must use a public domain name.
As an example I would change the following parameters:
var uri = new UriBuilder("https://www.coinpayments.net/api.php");
uri.SetQueryParam("success_url", "http://kugugshivom-001-site1.atempurl.com/Home/SuccessResponse");
uri.SetQueryParam("cancel_url", "http://kugugshivom-001-site1.atempurl.com/Home/FailiureResponse");
uri.SetQueryParam("ipn_url", "http://kugugshivom-001-site1.atempurl.com/Home/CoinPaymentsIPN"); // Public ActionResult CoinPaymentsIPN()
Since you are creating your own gateway you also need to implement it properly as described in the documentation at CoinPayments API and Instant Payment Notifications (IPN).
I have tested your success_url endpoint, and got status code: 100 (when entering status:100). I see you use form-data, but I don't know if that's on purpose / required.
Postman POST http://kugugshivom-001-site1.atempurl.com/Home/SuccessResponse
In Body tab form-data is selected with Bulk Edit values:
ipn_version:1.0
ipn_type:api
ipn_mode:hmac
ipn_id:your_ipn_id
merchant:your_merchant_id
txn_id:your_transaction_id
status:100
As updated answer stated by #Gillsoft AB, you should need to use valid IPN URL from the code end. Also webhook would not work with localhost. thus, you should listen the request with live server.
Simplest way to check webhook response is to use online tool such as Webhook Tester, it will provide an URL which you have to set as your IPN URL, whenever server will sends the data, you can simply see it to the web. To check that, create one URL and set as your IPN URL as below:
uri.SetQueryParam("ipn_url", "https://webhook.site/#/457f5c55-c9ce-4db4-8f57-20194c17d0ae");
After that run the payment cycle from local machine, payment server will sends notification to that IPN URL.
Make sure you understood it right! success_url and cancel_url are for user redirection, you will not get any response code over there, inspection of seller's store URL give your exact same URL that you have been passing though, so it is recommended to use unique URLs for each order(i.e add order id at last to the URL) which will give you an idea which order payment has been done or canceled.
http://localhost:49725/home/SuccessResponse?orderid=123
In order to test your local code, add following changes and deployed it to server.
1) Add one new method which will listen IPN response
[ValidateInput(false)]
public ActionResult IPNHandler()
{
byte[] param = Request.BinaryRead(Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
//TODO: print string request
//nothing should be rendered to visitor
return Content("");
}
2) Pass IPN URL while creating a request:
public ActionResult IPN()
{
var uri = new UriBuilder("https://www.coinpayments.net/index.php");
...
..
uri.SetQueryParam("success_url", "http://localhost:49725/home/SuccessResponse");
uri.SetQueryParam("cancel_url", "http://localhost:49725/home/FailiureResponse");
uri.SetQueryParam("ipn_url", "http://localhost:49725/home/IPNHandler");
....
..
return Redirect(uri.ToString());
}
You will get all status code responses in IPNHandler method.
Hope this helps!

C# - ASP.NET Issue with sending multiple data with Response.Redirect

I have 2 Web Forms
Catalog.aspx
ViewItem.aspx
In Catalog.aspx, I have a DataList that is connected to my Database.
My database contains Item Name, Image url and Price.
I'm trying to send over these 3 values with Response.Redirect.
I found this code online that works well with sending over the Image url but I'm not sure how to add on more values to it
This is the code
Response.Redirect("WebForm2.aspx?ImageUrl=" + ((ImageButton)sender).ImageUrl);
Any ideas?
Try this.
you can append all the parameters and send along with redirect url
var redirectParams= string.Format("ImageUrl={0}&Name={1}&Price={2}",((ImageButton)sender).ImageUrl, Name, Price);
Response.Redirect("WebForm2.aspx?" + redirectParams);

C# screen scraping an ASP.NET web forms page - POST request not completely working

Please bear with me for this slightly long winded description but I'm having a strange problem with C# screen scraping an ASP.NET web forms page. The steps I'm trying to do are as follows:-
1) The site is secured using basic authentication over HTTPS so I need to login appropriately.
2) I'm performing a GET request on the page to retrieve the __VIEWSTATE value (darn thing does nothing if I don't set this thing!)
3) Once logged in there are several form fields to complete then a submit button which POST's the form to the server
4) When the submit button is pressed the form is POST'd to the server and response is the same page and form but now with an extra little HTML table at the bottom of the form with some data I need to get at.
I've so far managed to sort the login and form post using the WebClient class. I've used fiddler (and firebug) to check the POST field values that are being sent when completing the form normally using a browser. I can successfully get a response from the POST request with the data table in question appearing below the form as expected. The problem however is that although the table is populated with data it is populated with data I don't expect. The data that appears is if I completed the form in a browser as normal but with one particular parameter (a drop down list) set to a different value than I'm passing in my POST request to the server. I've confirmed using fiddler and firebug that I'm passing exactly the same POST parameters that are sent as normal using a web browser human completed form. I'm now totally stuck as to why this one parameter is not being 'taken into consideration' by the server?
The one difference is that this particular control is a select list and it performs a page reload or 'postback' when changed. However this doesn't seem to do anything apart from change some other select lists content later in the form.
I guess I'm asking is there anything else I'm missing that would cause this? I'm totally tearing my hair out on this one. Can anyone help? I've posted the code below (with addresses and parameters blanked out for privacy).
// a place to store the html
string responseBody = "";
// create out web client to handle the request
using (WebClient webClient = new WebClient())
{
// space to store responses from the remote site
byte[] responseBytes;
// site uses basic authentication over HTTPS so we'll need to login
CredentialCache credentials = new CredentialCache();
credentials.Add(new Uri(Url), "Basic", new NetworkCredential(Username, Password));
// set the credentials in the web client
webClient.Credentials = credentials;
// a place for __VIEWSTATE
string viewState = "";
// try and get __VIEWSTATE from the web site
try
{
responseBytes = webClient.DownloadData(Url);
viewState = GetHtmlInputValue(Encoding.UTF8.GetString(responseBytes), "__VIEWSTATE");
}
catch (Exception e)
{
bool cancel = false;
ComponentMetaData.FireError(10, "Read web page data", "Error whilst trying to get __VIEWSTATE from web page: " + e.Message, "", 0, out cancel);
}
// add our POST parameters (don't forget the __VIEWSTATE or it won't work as its an ASP.NET web page)
NameValueCollection requestParameters = new NameValueCollection();
// add ASP.NET fields
requestParameters.Add("__EVENTTARGET", __EVENTTARGET);
requestParameters.Add("__EVENTARGUMENT", __EVENTARGUMENT);
requestParameters.Add("__LASTFOCUS", __LASTFOCUS);
// add __VIEWSTATE
requestParameters.Add("__VIEWSTATE", viewState);
// all other form parameters
requestParameters.Add("btnSubmit", btnSubmit);
/* I've hidden the rest of the parameters hidden for privacy just in case */
// see if we can connect and get data
try
{
// set content type
webClient.Headers.Clear();
webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// 'POST' the form data using web client and hope we get a response
responseBytes = webClient.UploadValues(Url, "POST", requestParameters);
// transform the response to a string
responseBody = Encoding.UTF8.GetString(responseBytes);
}
catch (Exception e)
{
bool cancel = false;
ComponentMetaData.FireError(10, "Read web page data", "Error whilst trying to connect to web page: " + e.Message, "", 0, out cancel);
}
}
Please ignore the 'ComponentMetaData' references as this is part of SSIS script source.
Any ideas or help will be greatly appreciated - cheers!
RE: thanks for the quick responses, all I can say to those comments is...
There's the normal ASP session cookie but there's no values in the cookie (apart from the session ID of course), I figured as the site is using basic authentication not forms authentication I could just ignore the cookie - and as I'm getting into the site and getting data returned this was ok. I guess it's worth a try but I'll have to just alter the code to use the WebRequest class method instead...
As for the select list javascript, no there's no javascript changing the value of the select list after page load. The only javascript on the select list is an onchange event to do a 'postback' which only seems to change some other select lists on the form that are empty anyway in the final POST. Note I'm including all the POST parameters when generating the POST request even if they're empty and I'm also including all the 'web forms' special fields such as __VIEWSTATE, __EVENTTARGET etc...
I'm no expert in web forms (MVC man myself) but is there anything else that the web forms 'engine' is expecting? I've sent 1 header for the 'Content-Type' of 'application/x-www-form-urlencoded' but I've tried setting others such as copying the 'User-Agent' header from the original POST but this ends up with me getting a 500 error from the server, not sure why that would happen??
Here's the code for the 'GetHtmlInputValue' its a bit simple/basic and could be done better but:-
private string GetHtmlInputValue(string html, string inputID)
{
string valueDelimiter = "value=\"";
int namePosition = html.IndexOf(inputID);
int valuePosition = html.IndexOf(valueDelimiter, namePosition);
int startPosition = valuePosition + valueDelimiter.Length;
int endPosition = html.IndexOf("\"", startPosition);
return html.Substring(startPosition, endPosition - startPosition);
}
If I understand you correctly, then selecting an item in the dropdown will cause a POST to be performed, and the server alters the available options in another part of the form. The server will then include the current value of the dropdown in the __VIEWSTATE field value.
When you perform the scraping, you should make sure that the __VIEWSTATE contains the desired value for the dropdown. To investigate further, try to decode the viewstate from the server and see which values are sent back.

How to send an url in an email in a wp8 app

Is there a way to send a http link in a wp8 app? I'm using
EmailComposeTask emailComposeTask = new EmailComposeTask();
but whenever I include an http link in the body of my email, it just appears as regular text.
My http link is included in a default string, so it would kind of make sense, but I assumed that the email app receving the email would just detected the http://... and automatically converted it a link but that's not the case.
Should I include the http link within a specific tag??
Any ideas?
Thanks
You Would see link as normal Text in Body when Composing but in mail it would be seen highlighted as link
Try this :
EmailComposeTask task = new EmailComposeTask();
task.To = "Set Email here";
task.Subject = "Subject goes here";
task.Body = "Your Mesage goes here \n http://www.google.com";
task.Show();
I have attached Screen Capture of inbox.
When you called EmailComposeTask, It will show an mail edit page.
In this page, the http link can't be shown.
But when you send it, in the Sent folder, the mail can show http link.
And in the receiver's Inbox, it also can be shown.

Categories

Resources