redirect to an external url on form submit - asp.net-mvc

i have a form which on submit should redirect to an external URL to perform some action with my form data, as well as remain on the home page after successful submission. i used redirection, but this will make my second option possible, but not my first one. Please help..

You have different possibilities here. The first possibility is to set the action attribute of the form directly to the external url and add a returnurl hidden input parameter. When the form is submitted it will POST data to the external url to process and when it finishes processing the external url will use the returnurl parameter to redirect back to your home page.
Another possibility is to call the external url in your POST action using WebClient to send data for processing and return the same view:
[HttpPost]
public ActionResult Index(SomeViewModel model)
{
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "param1", model.Property1 },
{ "param2", model.Property2 },
};
// send values for processing to the external url
var result = client.UploadValues("http://externalurl.com", values);
// TODO: analyze result
}
return View(model);
}

You need to manually program for this. For example you can pass a returnUrl parameter (e.g. via the query string) to the second page and that page will be in charge of reading this parameter and perform a redirect of its own.

Related

Request.UrlReferrer.ToString() Not reload in IE only

I'm trying to redirect page on previous page when i click on currency menu. In this menu set selected currency in cookies and redirect to Request.UrlReferrer.ToString() so Request page automatic read cookies and apply currency.
Here is my code
public ActionResult Index(string currency)
{
HttpCookie cookie = new HttpCookie("Cookie");
cookie.Values["CODE"] = currency;
cookie.Values["sym"] = Currencies[currency];
cookie.Values["Name"] = CurrenciesName[currency];
string currencyname = GetCurrencySymbol(currency);
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
return Redirect(Request.UrlReferrer.ToString());
//return RedirectToRoute(Request.UrlReferrer.ToString());
}`
for example page1 have some item with amount in USD now user change currency then i send request to CurrencyController with above Action then return to same page1.
Above code working fine in all browsers but not working in IE 11.
give me some idea where I'm doing wrong.
Thanks
First and foremost, you should never rely on UrlReferrer. Its value comes from an HTTP header that is not guaranteed to be sent, and even if it is sent, it can be tampered with. By using it in the way you are, you're opening yourself up to CSRF and man-in-middle attacks.
The correct way to do something like this is to pass along the URL you want to return to. For example, if a user is on a URL like /foo/ and then clicks a link where you want to redirect them back to /foo/ afterwards, then the URL of the link should be something like: /bar/?returnUrl=/foo/.
Then, the action responding to /bar/ would do something like:
public ActionResult Bar(string returnUrl)
{
// do something
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
// redirect to default
}
The Url.IsLocalUrl check is to make sure that the return URL is a path on the current site, again, to prevent malicious attacks.

MVC Create URL Back to Original Page on Timeout

In my Controller I have a function which helps me check for any Session timeouts, this works fine and it directs the users to an error page. Unfortunately from here I really just have the option to go back to the homepage, what I would like is to create the functionality to take them back to the previous page.
Each page will have a form of ID attached in the query string (this isn't always called ID, but it is always a unique number to identify the object.
What I need is to try and get this ID (always the first parameter / key) and use this as a basis to create the ActionLink on the view. I can get the RawUrl using the ActionExecutedContext which contains the requesting raw URL, but I'm unsure how to actuall make this useful.
The following is the code which executes after my Action, it validates if the user has timed out and moves them to an error page. The ErrorId of -1001 is just to identify that this is a timeout. What I need is an ID, similar to what I can kind of see in the RawUrl property, which I can then use as part of the RedirectToAction to take the user back to the original page.
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.HttpContext.Session != null)
{
if (filterContext.HttpContext.Session.IsNewSession)
{
string cookie = filterContext.HttpContext.Request.Headers["Cookie"];
if ((cookie != null) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))
{
filterContext.Result = RedirectToAction("Error", new { errorId = -1001, errorMessage ="Your session has timed out.Please restart the application or click 'Home' below."});
return;
}
}
base.OnActionExecuted(filterContext);
}
}
... and it directs the users to an error page.
When making this redirect pass as query string parameter a ReturnUrl. This parameter will be the current request url.
Then inside the error page you will be able to use this ReturnUrl query string parameter to build an anchor or a form pointing to the initially requested resource. For example:
Go back

return Json will redirects to another view when Url specified

When you do return Json(...) you are specifically telling MVC not to use a view, and to serve serialized JSON data. Your browser opens a download dialog because it doesn't know what to do with this data.
i got the above information from below link
How to return Json object from MVC controller to view
when i give this below code in some action result
return Json(new { Url = "sep/employee"}
whether it will redirect to specified action ? how it redirects to the URl ?
for this case why i cant use return RedirectToAction("sep/employee").
how return Json code redirects to action which specified in the Url.
ex:
public ActionResult Index()
{
................................
return Json(new { Url = "sep/employee"}
}
public ActionResult employee()
{
....................
}
what is the difference b/s redirectaction and return Json
You return the following line to an ajax success call
return Json(new { Url = "sep/employee"});
you then need to specify where to redirect to the new page
success: function(result) {
window.location.href=result.Url;
}
RedirectToAction simply returns 302 code to your browser with URL telling where the browser should redirect to. The browser immediately makes yet another call to the server to that URL obtained from redirection response.
RedirectToAction internals are:
Construct redirection url from parameters passed to RedirectToAction
Return new RedirectToRouteResult
In ExecuteResult of RedirectToRouteResult you can find the following line:
context.HttpContext.Response.Redirect(destinationUrl, endResponse: false);
which is merely returning 302 with redirection URL. More info - look at source code here.
Returning JSON data simply returns JSON serialized object to your browser. Is not meant to do any redirect. To consume such a result you will likely call the server using $.ajax:
$.ajax({
url: 'sep/employee',
type: 'POST'
success: function(result) {
// handle the result from the server, i.e. process returned JSON data
}
});
ExecuteResult of JsonResult just serializes passed CLR object to the response stream, which lands in your browser after response is fully received. Then you can handle such response in JavaScript code.
EDIT:
You of course can mimic 302 redirection by returning Json like
return Json(new { Url = "redirectionUrl"}
and at client side handle it like
$.ajax({
url: 'sep/employee',
type: 'POST'
success: function(result) {
// mimic the 302 redirection
windows.location.href = result.Url
}
});
although IMHO it should be avoided since you reinvent MVC infrastructure and enlarge your code base.
whether it will redirect to specified action ? how it redirects to the URl ?
I assume you mean to ask, "will it redirect to specified action? how will it redirect the the URI?"
To answer your question: How it redirects to the URL?
In your example it will redirect to the URL, if you made the HTTP request as AJAX and that you will explicitly handle the resulting HTTP response to actually redirect to the URL that you received. So your view should have something like this:
$.ajax({
url: '{your controller}/index',
type: 'GET'
success: function(url) {
// write code to redirect to the URL
// example:
// window.navigate(url)
}
});
If your view does not have anything that, then it will not redirect. You did not post your view, so I am assuming it just a normal page load.
Your next question, what is the difference b/s redirection and return Json?
If you really just want to redirect then do RedirectToAction from your controller, that is exactly what it is for. You can do the same effect using AJAX and JSON to be able to redirect, but AJAX and JSON serves a much wider purpose than just redirecting and in most cases (unless you have very good reasons) you probably will not want replace RedirectToAction with that approach.

Redirect after POST doesn't change URL

I'm using the "Redirect After Post" (http://en.wikipedia.org/wiki/Post/Redirect/Get) pattern to solve the problems with refreshing that it solves, but I'm not seeing the URL change after the POST and subsequent GET.
Here is my setup:
I have a form with some pretty extensive client-side validation, then submit.
#using (Html.BeginForm("AddItem", "Order", FormMethod.Post, new { Id = "addItemForm" }))
{
// form stuff
}
Client-side validation:
$('#addToOrder').click(function () {
// do a bunch of validation stuff.
}
if (criteriaMet) {
$('#addItemForm').submit();
}
"AddItem" controller:
public class OrderController {
[HttpPost]
public ActionResult AddItem(long? orderId, long menuItemId)
{
if (oneConditionIsTrue)
{
return RedirectToRoute("NamedRoute1", new { RouteValueDictionary values });
}
else
{
return RedirectToRoute("NamedRoute2", new { RouteValueDictionary values });
}
}
public class NamedRouteController
{
public ActionResult NamedRouteAction
{
// do some stuff
if (mobile)
{
return View("MobileView", model);
}
else
{
return View("RegularView", model);
}
}
After redirecting from the POST action (AddItem), I can step things through the GET action to the return (either one). I would expect the URL in the browser after all of this to be http://mydomain.com/NamedRoute/NamedRouteAction but it's http://mydomain.com/Order/AddItem. Why is this? Shouldn't the RedirectToRoute change the URL?
What am I missing?
I suspect that the controller action is somehow invoked with an AJAX request. For example this could happen if you are using jQuery Mobile or something. Or maybe there's some other script that you have written doing this - it hijacks the form submission and sends an AJAX request instead. And since it is an AJAX request, you cannot possibly expect that the url in the client browser would ever change - that's the whole point of AJAX - stay on the same page.
This could be very easily verified by using a javascript debugging tool such as FireBug. Simply look at the Network tab and see if the POST request was an AJAX request. In the Net tab find the request and see if there's the following request header:
X-Requested-With: XMLHttpRequest
jQuery appends this HTTP header to all AJAX requests it sends.
So basically if you expect a redirect to happen after a POST request you shouldn't use AJAX to submit your form. Or to be more precise: the redirect happens on the server side (once again you will be able to see it in FireBug - the 302 status code) and then the XMLHttpRequest simply follows this redirect but the client browser will not change its current location.

Return to referring page

I am using an authentication attribute on some of my actions in an asp.net mvc page to refer people to a login screen if they have not authenticated. My problem is returning them to the referring page after they have logged in. I was just keeping track of the referring action and referring controller but that becomes problematic when I also need to keep track of some parameters. Is there some nifty built in trick about which I don't know?
In case you're using FormsAuthentication, when ASP.NET redirects a user to the login page, the URL looks something like this:
http://www.mysite.com/Login?ReturnUrl=/Something
The login form's action attribute should have the same ReturnUrl parameter (either as hidden input or as part of Url) so that FormsAuthentication can pick it up and redirect, e.g.
<form action="Login?ReturnUrl=<%=Html.AttributeEncode(Request.QueryString["ReturnUrl"]) %>"></form>
or
<form><input type="hidden" name="ReturnUrl" id="ReturnUrl" value="<%=Html.AttributeEncode(Request.QueryString["ReturnUrl"])"%> /></form>
What I did to achieve that result might be overdoing it, and I'd like to see some other methods as well. However, here's my code.
Please note it's using Moq to mock a context... And, I haven't done anything with the querystring yet (my routes don't contain any querystrings).
var urlReferrer = Request.UrlReferrer;
if (urlReferrer != null)
{
var url = "~" + Server.UrlDecode(urlReferrer.PathAndQuery);
// get routecollection
var routeCollection = new RouteCollection();
GlobalApplication.RegisterRoutes(routeCollection);
// mcok context
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
context.Expect(ctx => ctx.Request).Returns(request.Object);
// mock request
// TODO: convert querystring to namevaluecollection
// now it's just stripped
if (url.IndexOf('?') > 0)
{
url = url.Substring(0, url.IndexOf('?'));
}
var mock = Mock.Get(context.Object.Request);
// TODO: insert namevaluecollection of querystring
mock.Expect(req => req.QueryString).Returns(new NameValueCollection());
mock.Expect(req => req.AppRelativeCurrentExecutionFilePath).Returns(url);
mock.Expect(req => req.PathInfo).Returns(string.Empty);
// get routedata with mocked context
var routeData = routeCollection.GetRouteData(context.Object);
var values = routeData.Values;
return RedirectToAction(routeData.Values["action"].ToString(), values);
}
As I said, it's maybe a bit overcomplicated :)
You should always ensure that the referring URL is within your domain and a plausible string that they could be coming from. Otherwise this has the potential of being used with flash or other client side technologies to do things like response splitting or other attacks, known and unknown.
The HTTP referer is user input, and it should be validated like any other.

Resources