MVC5 redirect to internal url - asp.net

Is there a way to link to an internal Url in mvc5?
I get the url like so: Source = Request.RawUrl
this returns: "/Clients/AddNote"
but it can also have parameters: "/Clients/AddNote/12?items=10"
This is the code that i have so far:
string[] url = Source.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string Controller = url[0];
string Action = url[1];
try{
string id = url[2];
return RedirectToAction(Action, Controller, new { id = id});
}
catch{}
return RedirectToAction(Action, Controller);
this works good when there is only an ID ad parameter but this code does not handle the named parameters like: ?items=10
is there a way that i can just say: return RedirectToAction("/Clients/AddNote/12?items=10");?

Have you tried to use: Request.AbsoluteUri ?

Related

Using Web API redirect to angular html page

I want to redirect an HTML page using WEB API. I'm using ASP.Net Web API as a back-end and a front-end is on Angular 5. Here is my code. Here is my updated API source code.
[System.Web.Http.HttpGet]
public string[] Payment(string uri)
{
try
{
RegistrationRequestX reg = new RegistrationRequestX();
reg.Customer = "Test Api";
reg.Channel = Channels.Web;
reg.Language = "EN";
reg.Amount = 10;
reg.OrderID = "1234";
reg.OrderInfo = "test info";
reg.OrderName = "testing order";
string retPath = uri;
retPath = retPath.Replace("payment", "confirmation");
reg.ReturnPath = retPath;
RegistrationResponseX res = new RegistrationResponseX();
res = client.Register(reg);
client.Close();
string[] sess = new string[2];
sess[0] = paymentPortalURL;
sess[1] = transactionID;
return sess;
}
catch (Exception)
{
throw;
}
}
You can return the redirect uri back to angular client with status code 302.
At angular, you should check the returned status code. If it is 302 then redirect to returned redirect url.
Use the window.location.href in your angular to set the first element of the array that you return to redirect to the Url that you expected
You can change a return type of the cotroller method on IHttpActionResult and return using Ok and Redirect methods, inherited from ApiController.
For example see code below if you want to either return string[] with ok code (200) or a redirect (302) with Location response header with provided redirect link, depending on some condition:
[System.Web.Http.HttpGet]
public IHttpActionResult Payment(string uri)
{
string[] sess = ...
if (someRedirectCondition)
return Redirect("http://a.link.to.your.html.page");
else
return Ok(sess); // A method type is inferred to Ok<string[]>(string[] content)
}

Query string parameter vs regular parameter ASP.Net MVC 5

I have been working on desktop applications mostly and thought to learn web development using ASP.Net MVC5 and thus going through the book by Jon Galloway. So I was reading about how you can pass the parameters to action methods using query string like
/Store/Browse?genre=Disco
or directly embed them in the url like
/Store/Details/5
Now the controller code that I wrote (taken from book) is below :
namespace MvcMusicStore.Controllers
{
public class StoreController : Controller
{
// GET: Store
public string Index()
{
return "Hello from Store.Index()";
}
public string Browse(string genre)
{
string message = HttpUtility.HtmlEncode("Store.Browser, Genre = " + genre);
return message;
}
public string Details(int id)
{
string message = "Store.Details, ID = " + id;
return message;
}
}
}
The url opens fine and the actions return the message as expected. But just to try I tried to pass the genre value by embedding it in the url like
/Store/Browse/Rap
but that doesn't work like it did for the Details() action. I thought it may have to do something with the datatype of genre, so I tried changing the data type of id in Details() to string as below :
public string Details(string id)
{
string message = "Store.Details, ID = " + id;
return message;
}
}
and opened the url
/Store/Details/5
and the Details() action returns message with id value 5, but when i do the same for Browse() action
/Store/Browse/Rap
the action doesn't return the message with genre value "Rap". I tried to pass the genre value and removed the html encoding to see if that had anything to do with it, but it didn't.
I looked at the post here but that didn't help either. Any comments appreciated.
Your using the Default route which is defined as
url: "{controller}/{action}/{id}",
and expects a value for id. When you use /Store/Browse/Rap, then the value of the 3rd segment ("Rap") will be bound to a paramater named id, but your Browse() method does not contain one (its named genre).
Either change the name of the parameter so its
public string Browse(string id)
and the value of id will be "Rap",
Or create a specific route definition and place it before the Default route (and keep the Browse() method as is)
routes.MapRoute(
name: "Browse",
url: "Store/Browse/{genre}",
defaults: new { controller = "Store", action = "Browse", genre = UrlParameter.Optional }
);
... // default route here
Side note: You do not need to change the type of the parameter in the Details method if your always passing a value that is a valid int

ASP MVC - How can I change the base url of the request for Url.Content?

Let's say I have a request with the following url:
foo.bar.com/do/something
The "something" action of the "do" controller returns a view with an image that has the following url: foo.bar.com/content/image.png (generated by the helper Url.Content) - this is just an example, my actual page has a lot of images
I want to know what can I do in the action to change the behaviour of the Url.Content so that it generates my image url with the url localhost/content/image.png.
This probably is not the best solution, but it may work for you:
You could write a extension such as the one below to achieve this:
// Determine if gen localhost or the normal hostname
public static bool IsUseLocalhost { get; set; }
public static string ContentFullPath(this UrlHelper url
, string virtualPath, string schema = "", string host = "")
{
var result = string.Empty;
Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
if (string.IsNullOrEmpty(schema))
{
schema = requestUrl.Scheme;
}
if (string.IsNullOrEmpty(host))
{
if (IsUseLocalhost)
{
host = "localhost";
}
else
{
host = requestUrl.Authority;
}
}
result = string.Format("{0}://{1}{2}",
schema,
host,
VirtualPathUtility.ToAbsolute(virtualPath));
return result;
}
In the Action you can set the static IsUseLocalhost to true to turn all gen url with localhost.
Then in the view use it as:
#Url.ContentFullPath("~/content/image.png")
If you want to set explicity host, then in the view use it as:
#Url.ContentFullPath("~/content/image.png", host: "localhost")

How to handle a POST request to a URL that contains route parameters?

I'm working on an ASP.NET MVC4 web app, and I have a controller method for handling a GET request with an id in the URL, like so ...
[PortalAuthorization]
public ActionResult View(int id)
{
// get the individual ftp log
PortalFTPLog log = PortalFTPLogs.Get(id);
if (log == null)
{
TempData["Error"] = "The provided ftp log id does not exist.";
return RedirectToAction("Index");
}
// get the available matters to tie uploads to
ViewBag.matters = PortalMatters.Get();
return View(log);
}
In my view for this controller method, I have a form so that they can update it, that I want to POST back to the same URL. A URL like foo.com\items\1. Thats what the function above handles.
How do I make a function that handles a POST request for a function that requires a parameter, though? IN previous POST handlers I create a FormsCollection param, but when I add it to the param list for this function, the id param is null.
[HttpPost]
[PortalAuthorization]
public ActionResult View(FormCollection collection, int id)
{
PortalFTPLog log = PortalFTPLogs.Get(id);
if (log == null)
{
TempData["Error"] = "The provided ftp log id does not exist.";
return RedirectToAction("Index");
}
// update the matter id and save to database
log.Matter = Convert.ToInt32(collection.Get("matter"));
log.Save();
TempData["Notice"] = "The FTP log meta data has been updated.";
return RedirectToAction("View", new { id = id });
}
You need to provide RouteValues in Html.BeginForm on your View:
#using (Html.BeginForm(new {id = someIntIdValue}))
{
// Your form code
}

Facebook authentication response parameters are wrong -> infinite request loop

I an new to the facebook API and after some work I encountered a problem.
First, I am using the facebook SDK for communication with the facebook APIs.
In my app settings I chose that the response of the OAuth dialog should be query string instead of URI fragment.
On my server I got the following code:
void Page_Load()
{
string url = Request.Url.AbsoluteUri;
Facebook.FacebookOAuthResult result = null;
if (!Facebook.FacebookOAuthResult.TryParse(url, out result))
{
string redirectUrl = PivotServer.Helpers.GetFacebookOAuthUrl();
Response.Redirect(redirectUrl);
}
}
And thats my helper method:
public static string GetFacebookOAuthUrl()
{
FacebookOAuthClient oauth = new FacebookOAuthClient
{
AppId = "149637255147166",
AppSecret = "xxx",
RedirectUri = new Uri("http://mydomain.com/")
};
var param = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "popup" }
};
Uri url = oauth.GetLoginUrl(param);
return url.AbsoluteUri;
}
I ran my page on a web server (IIS). When I open the page the first time I am asked to log in to facebook, which is alright, but then I ran into an infinity loop, because the Auth Token Parameter (from facebook) is an URI fragment instead if a query string (which I wanted (see picture above)).
The response URI looks like
http://mydomain.com/#access_token=AAACIGCNwLp4BAMccSoliF5EMGJm0NPldv5GpmBPIm9z7rRuSkiia7BM0uhEn1V88c8uOlWOfGc3C8sFC9tq90Ma0OwIm0tWLNU5BBAZDZD&expires_in=0&base_domain=mydomain.com
instead of
http://mydomain.com/?code=AAACIGCNwLp4BAMccSoliF5EMGJm0NPldv5GpmBPIm9z7rRuSkiia7BM0uhEn1V88c8uOlWOfGc3C8sFC9tq90Ma0OwIm0tWLNU5BBAZDZD&expires_in=0&base_domain=mydomain.com
Is that a bug from the OAuth API, or what am I doing very wrong here?
It's an issue with IE. Be sure to have a p3p header in each response from your server.
It has been too easy:
var param = new Dictionary<string, object>
{
{ "response_type", "code" }, // <--- "code" instead of "token"
{ "display", "popup" }
};

Resources