Getting URL of rewritten request? - c#

All the users on my site have public-facing profile pages. I am using URL rewriting to change urls from the form http://mysite.com/profile.aspx?id=sdsdfsdsdfsdfdsdffsdfsdf into http://mysite.com/Username like this (in my global.asax file):
static Regex _handleRegex1 = new Regex("/(?<hndl>[\\w]+)/?$", RegexOptions.Compiled);
void Application_BeginRequest(object sender, EventArgs e)
{
System.Text.RegularExpressions.Match handleMatch = _handleRegex1.Match(Request.Url.LocalPath);
if(handleMatch.Success){
String handle = handleMatch.Groups[1].Value;
using (SqlQuery query = new SqlQuery("[dbo].[sp_getUserIdByHandle]"))
{
try
{
query.AddParameter("#handle", handle, System.Data.SqlDbType.NVarChar, false);
query.AddParameter("#userId", new Guid(), System.Data.SqlDbType.UniqueIdentifier, true);
query.ExecuteNonQuery();
Object userId = query.GetOutParameter("#userId");
if (userId == DBNull.Value)
{
Response.Redirect("~/default.aspx");
}
else
{
Context.RewritePath(string.Format("~/profile.aspx?id={0}&{1}", userId, Request.QueryString));
}
}
catch (Exception ex)
{
}
}
}
}
This works fine. However, if I do a postback to the server, the URL changes from something like /username to the form /profile?id=5ab47aa3-3b4d-4de6-85df-67527c9cdb52&, which I want to hide from the user.
I thought about doing something like Response.Redirect(Request.RawUrl); to sent the user back to the right page. However, Request doesn't seem to contain any information about the desired URL.
Is there any way to find the pre-rewritten URL?

What platform are you on? If IIS 7 you would be best off using IIS URL Rewrite 2.0. You can find some suggestions on dealing with postback using this.

I suggest you use Routing, that way you can write your code the ASP.NET way but still have the Urls you want:
Routing with ASP.NET Web Forms

Related

asp.net webforms google login

I have been searching the net for a solution to use a users google account for authentications on a asp.net webform application.
All I want is that the user login to his google account and return to my webform application with display name, google ID and Email form there I will take care of the rest.
I have tried http://dotnetopenauth.net/, Google .Net Api but I never found a working example.
Can anybody point me in the right direction with a example that works. (C# or vb.net)
Have you thought about giving Nemiro.OAuth a try? It's easy to set up, supports asp.net and winforms, and the online documentation is very detailed.
protected void RedirectToLogin_Click(object sender, EventArgs e)
{
// gets a provider name from the data-provider
string provider = ((LinkButton)sender).Attributes["data-provider"];
// build the return address
string returnUrl = new Uri(Request.Url, "ExternalLoginResult.aspx").AbsoluteUri;
// redirect user into external site for authorization
OAuthWeb.RedirectToAuthorization(provider, returnUrl);
}
protected void Page_Load(object sender, EventArgs e)
{
var result = OAuthWeb.VerifyAuthorization();
Response.Write(String.Format("Provider: {0}<br />", result.ProviderName));
if (result.IsSuccessfully)
{
// successfully
var user = result.UserInfo;
Response.Write(String.Format("User ID: {0}<br />", user.UserId));
Response.Write(String.Format("Name: {0}<br />", user.DisplayName));
Response.Write(String.Format("Email: {0}", user.Email));
}
else
{
// error
Response.Write(result.ErrorInfo.Message);
}
}
You can also follow this tutorial for a step-by-step instruction on how to use OAuth with Nemiro.OAuth library.

Redirect to different pages for request coming from subdomain site

I have main site and its subdomain site.
When user is entering main site url www.mysite.com it should get redirected to 'Login.aspx'
When user is entering sub domain site url sample.mysite.com it should get redirected to 'Welcom.aspx'
To achieve this what is the best way to do ?
Changes in IIS settings ?
Modify Code in Global.asax
Create Dummy Page for redirection
What code i have to wrote if i required to modify global.asax ?
Personally I will choose 2nd option, modify the Global.asax file.
void Application_BeginRequest(Object source, EventArgs e)
{
string host = HttpContext.Current.Request.Url.Host.ToLower();
if (host == "www.mysite.com")
{
//Incase if you are using any session
if (Session["User"] == null)
Response.Redirect("Login.aspx");
else
{
//validate the session
Response.Redirect("Home.aspx");
}
}
else if (host == "sample.mysite.com")
{
Response.Redirect("Welcome.aspx");
}
}
To achieve the redirection , modify the code in global.asax will be the best one

My ReturnUrl is duplicating

I have a page that if you don't have the cookie i want it redirects you to the page the cookie is created. Basically if you didn't tell me you are old enough you gotta redirect to a page and give me your age. Long story short if i get redirected to this page where i am asking for you age and the end user doesn't decide to give me there age and click on that same page or another page. My code is adding onto the existing string.
protected void Page_Load(object sender, EventArgs e)
{
string referrer = Request.UrlReferrer.ToString();
if (Request.Cookies["Age"] == null)
Response.Redirect("/AgeRestricted/?ReturnUrl=" + referrer);
}
if I call this page to load multiple times my URLS can get really ugly.
http://localhost:14028/AgeRestricted/?ReturnUrl=http://localhost:14028/AgeRestricted/?ReturnUrl=http://localhost:14028/
it is like it is concatenating onto the existing. Is there a way for me to prevent this?
I basically want to have it so that i only have 1 param in my ReturnUrl QueryString and so that it won't duplicated if that already has a value.
You can do this by using the Uri class to obtain only the parts of the referrer without the query string. For example:
if (Request.Cookies["Age"] == null)
{
string referrer = Request.UrlReferrer.GetLeftPart(UriPartial.Path);
Response.Redirect(referrer);
}
For more information on GetLeftPath, see: http://msdn.microsoft.com/en-us/library/system.uri.getleftpart.aspx
Here is the code that fixed the problem. Don't know why my last answer was deleted.
string url = HttpContext.Current.Request.Url.AbsoluteUri;
if (Request.Cookies["Age"] == null)
Response.Redirect("/AgeRestricted/?ReturnUrl=" + url);

"The post's links must direct to the application's connect or canvas url"?

I'm building an application for WP7 using the Facebook C# SDK. When I attempt to post a message to a users wall (Just a plain message) everything works fine. But when I attempt to post a link to the users wall I get this exception message:
(OAuthException) (#100) The post's links must direct to the application's connect or canvas URL.
Does anyone know how to fix this? I have heard of canvas applications but I didn't think this applied to a phone app. Perhaps this is a setting on Facebook?
Any feedback is appreciated.
Here is the code I used to post to facebook:
private void button1_Click(object sender, RoutedEventArgs e)
{
_fbClient.PostCompleted +=
(o, er) =>
{
if (er.Error == null)
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show(er.Error.Message);
}
};
var args = new Dictionary<string, object>();
args["name"] = "Hello World!!";
args["link"] = "http://www.nfl.com";
args["caption"] = "";
args["description"] = "";
args["picture"] = "";
args["message"] = "Hello World from application.";
args["actions"] = "";
FacebookAsyncCallback callback = new FacebookAsyncCallback(this.postResult);
_fbClient.PostAsync("me/feed", args, callback);
}
private void postResult(FacebookAsyncResult asynchResult)
{
MessageBox.Show("Success");
}
NOTE: If I remove the string from "link" it works.
I found a solution to my problem "here". In your app settings within Facebook you have to set "Stream Post Url Security" to false. Hope this helps someone.
Go to the Facebook App. Edit its settings. On the Advanced settings page, disable the "Stream post URL security" option.

Webform routing home page in a folder like mvc rather than root of site

I've got webform routing setup on my asp.net webforms 3.5sp1 project. I would like to have the files for the site in a directory called content including the home page as I would like to run multiple sites using the same system.
In MVC there is a blank default page and the home page is in a folder called home. I can't seem to replicate this behaviour using web form routing but would like to. The blank page is always hit first. the route handler is hit second - it recognises that the request is for the home page and sets up the routing page but is not used. the route handler code is simple:
public string VirtualPath { get; private set; }
public IHttpHandler GetHttpHandler(RequestContext
requestContext)
{
string file = requestContext.RouteData.GetRequiredString("File");
string id = requestContext.RouteData.GetRequiredString("Id");
string queryString = "?menuid=" + id;
VirtualPath = "~/" + file;
HttpContext.Current.RewritePath(
string.Concat(
VirtualPath,
queryString));
var page = BuildManager.CreateInstanceFromVirtualPath
(VirtualPath, typeof(Page)) as IHttpHandler;
return page;
}
Is there anyway I can do this?
Update
Here is my global.asax route code:
public static void RegisterRoutes(RouteCollection routes)
{
Domain.RepositoryFactory repo = new RepositoryFactory();
foreach (var x in repo.MenuRepository.GetAllEnabledGetMenus())
{
if (string.IsNullOrEmpty(x.Url))
{
//add default
System.Web.Routing.RouteTable.Routes.Add(
new Route("Default.aspx",
new RouteValueDictionary(new { File = x.FileName,
Id = x.Id.ToString() }),
new CoreRouteHandler()));
}
else
{
string url = x.Url;
if(x.Url.StartsWith("/"))
{
url = url.Remove(0, 1);
}
System.Web.Routing.RouteTable.Routes.Add(
new System.Web.Routing.Route(url,
new RouteValueDictionary(new {File = x.FileName,
Id = x.Id.ToString()}),
new CoreRouteHandler()));
}
}
}
In my project I was needed to redirect all calls like www.site.com/MyPage to /Pages/MyPage.aspx. Was done by using HttpModule. Sample code below:
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (app.Context == null || app.Context.Response == null)
return;
String sourceUrl = String.Empty;
try
{
sourceUrl = app.Request.FilePath.TrimStart('/').TrimEnd('/').ToLower();
if (global::MyProject.Global.UrlShortcuts.ContainsKey(sourceUrl))
{
String newUrl = global::MyProject.Global.UrlShortcuts[sourceUrl];
app.Context.RewritePath(newUrl, string.Empty, app.Request.QueryString.ToString(), false);
}
else
{
}
}
catch (Exception Ex)
{
// handle your exception here
}
}
The minor issue was with hoster's IIS as I was unable to configure it to process all requests using ASP.NET. So I had to come up with blank placeholder .aspx files for pages (e.g. www.site.com/MyPage/default.aspx) created dynamically at application startup if it's running under IIS.
String server = Context.Request.ServerVariables["SERVER_SOFTWARE"];
// IIS puts some stuff here, WebDev server leaves the field empty
ok I got it working bit of a doh! moment.
I found this link while googling:
http://blog.ysatech.com/post/2010/07/11/ASP-NET-4-URL-Routing-Default-Page.aspx
all I needed to do was leave the route blank and delete the default.aspx file from the root of the site.
I also copied in the default system.webserver bis from a new MVC project as i think what i had there wasn't right. I'm upgrading an old project and so think it wasn't configured 100%. specifically: was missing.

Categories

Resources