I have a hyperlink on a .aspx page
<asp:HyperLink ID="hlTest" runat="server" NavigateUrl="#">Test Link</asp:HyperLink>
On the code behind page I have:
string link = "http://myDoman/myEmailAttachments/1436/" + HttpUtility.HtmlEncode("Picture of Jim&John.jpg");
hlTest.NavigateUrl = link;
This generates a url that looks like:
http://myDomain/myEmailAttachments/1436/Picture%20of%20Jim&John.jpg
This causes a message to be shown: A potentially dangerous Request.Path value was detected from the client (&).
I have tried using Server.Urlencode. This produces a url that looks like ...
http://myDomain/myEmailAttachments/1436/Picture+of+Jim%26John.jpg
This causes the same message to be shown: A potentially dangerous Request.Path value was detected from the client (&).
If I have a file called ...
Picture of Jim&John.jpg
... How can I get it into a hyperlink so it will actually go and get the file? Thank you for any help.
That is because you don't want to HTML encode (HttpUtility.HtmlEncode), but URL encode (HttpUtility.UrlEncode). Then the %26 will be rewritten as & which is the correct format for an URL. That will prevent ASP.NET see it as potentially malicious.
string link = "http://myDoman/myEmailAttachments/1436/"
+ HttpUtility.UrlEncode("Picture of Jim&John.jpg")
;
Related
I am trying to use oauth2.
I make a get request, and then I get redirected at a callback url that I have set up before. The problem lies in the fact that the url parameters get preceded by the # sign and thus php, .net can't read them!
I get redirected in the following url in my browser:
http://localhost:1787/About.aspx?#access_token=f3EToovT2bQNNOQ&token_type=bearer&merchant_id=A6BGD4BH&response_type=token
Request.Params is empty, request.query string is empty. Even when I use php and print the $_REQUEST array still is empty!
How is this possible?
Whatever comes after the # doesn't mark as DATA being sent to the server, but a hash on the client side.
Try redirect using JavaScript only the hash:
window.location = window.location.pathname + '?' + window.location.hash.substring(1);
When I use HttpUtility.UrlEncode to encode a Url I end up getting a server error.
ASP.Net code:
NavigateUrl=<%# HttpUtility.UrlEncode(string.Concat("UpdateMember.aspx","?groupId=", DataBinder.Eval(Container.DataItem, "GroupID").ToString())) %>
Url:
http://localhost/UITest/MM/UpdateMember.aspx%3fgroupId%3d0032409901
which results in "HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable."
However using:
NavigateUrl=<%# string.Concat("UpdateMember.aspx","?groupId=", DataBinder.Eval(Container.DataItem, "GroupID").ToString()) %>
results in the Url:
http://localhost/UITest/MM/UpdateMember.aspx?groupId=0032409901
which works out fine. Am I doing something incorrectly?
You shouldn't encode the entire URL, atleast not the 1st "?" symbol. If you encode the ? too then your application looks for a file with the name & extension "UpdateMember.aspx%3fgroupId%3d0032409901" which doesn't exist.
Probably, this is what you should do.
http://localhost/UITest/MM/UpdateMember.aspx?groupId%3d0032409901
HttpUtility.UrlEncode() URL-encodes a string
That means that it escapes all special characters from the string so that you can insert it as part of a URL without any characters being parsed as URL modifiers.
You use this kind of escape function when inserting arbitary text as part of a URL.
I am trying to use following code to get referring url in global.asax session_start:
HttpContext.Current.Request.ServerVariables["HTTP_REFERER"]
I tried using Request.UrlReferrer.AbsoluteUri but UrlReferrer is also null.
but I am getting null. Can you please suggest me what is wrong or alternative?
Not all user-agents send a referrer, some proxies/intermediaries strip the referrer, and often there simply is no referrer.
Just check whether Request.UrlReferrer == null at some point; if it is, don't try looking at Request.UrlReferrer.AbsoluteUri.
There is nothing "wrong" here, and nothing you can do about it. If you don't know where they came from, you'll just have to live with that.
I know this answer is about 2 1/2 years late but I couldn't find a thorough write up on the UrlReferrer property so I figured I would add this info here. #MarcGravell's answer is correct for the most part, but it misses one other possibility. The value for referrer specified in the HTTP header can also be an invalid uri.
For this reason, you should be careful when using the UrlReferrer property on HttpRequest. If you look at the code that is executed when UrlReferrer is called using something like ILSpy, you'll see that it tries to parse the value from the request header. If the value in that header is not a valid uri, you will get a System.UriFormatException.
What this means is that simply checking UrlReferrer for null before trying to access AbsoluteUri could leave you with unhandled exceptions if the referrer is not a valid uri. If you want either a valid Uri or null, you'll have to use Request.ServerVariables["HTTP_REFERER"] and then Uri.TryParse, or you'll have to wrap the Request.UriReferrer == null check in a try-catch.
I put together a quick demo to show the behavior of the UrlReferrer property. Take the following page as an example:
<%# Page Language="C#" AutoEventWireup="true" %>
<html><body>
<table border="1">
<tr><td>Referrer</td><td><%= GetUrlReferrer() %></td></tr>
</table>
</body></html>
<script runat="server">
public string GetUrlReferrer()
{
try
{
return Request.UrlReferrer == null ? "(None)" : Request.UrlReferrer.ToString();
}
catch (Exception ex)
{
return Request.ServerVariables["HTTP_REFERER"] + " (from Server Variable)";
}
}
</script>
Set up this page to run under http://localhost/urlreferrertest.aspx, and then try calling it from Powershell with an invalid Uri for the referrer:
> $client = new-object System.Net.WebClient
> $client.Headers.Add("Referer", "http://www%2etest%2e.com/test.html")
> $client.DownloadString("http://localhost/urlreferrertest.aspx")
If you step through the code you'll see that the call to Request.UrlReferrer throws an exception, and that http://www%2etest%2e.com/test.html is returned by accessing the ServerVariable.
I am using the code,
string loadFile = HttpContext.Current.Request.Url.AbsoluteUri;
// this.Response.ClearContent();
// this.Response.ClearHeaders();
this.Response.AppendHeader("content-disposition", "attachment; filename " + filename);
this.Response.ContentType ="application/html";
this.Response.WriteFile("C:\\Users\\Desktop\\Jobspoint Website\\jobpoint3.0\\print.aspx");
this.Response.Flush();
this.Response.Close();
this.Response.End();
to download an aspx page in asp.net C#.. But its only showing the html tags and static values... How can I save the entire page without html tags and with the values that retrieved from the database?
Thanks...
Leema
Use WebClient for this. It will download your file.
If I have understood correctly, one option would be to actually make a request to the web server using WebClient for example. And then write the response to that request to the Response.OutputStream. This means that the server will actually make a second request to it self and then send the response to the second request back to the client.
This way you will have the web server actually process the request and return the resulting HTML back to you rather than just the raw aspx page.
I need to check that our visitors are using HTTPS. In BasePage I check if the request is coming via HTTPS. If it's not, I redirect back with HTTPS. However, when someone comes to the site and this function is used, I get the error:
System.Web.HttpException: Server
cannot append header after HTTP
headers have been sent. at
System.Web.HttpResponse.AppendHeader(String
name, String value) at
System.Web.HttpResponse.AddHeader(String
name, String value) at
Premier.Payment.Website.Generic.BasePage..ctor()
Here is the code I started with:
// If page not currently SSL
if (HttpContext.Current.Request.ServerVariables["HTTPS"].Equals("off"))
{
// If SSL is required
if (GetConfigSetting("SSLRequired").ToUpper().Equals("TRUE"))
{
string redi = "https://" +
HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToString() +
HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"].ToString() +
"?" + HttpContext.Current.Request.ServerVariables["QUERY_STRING"].ToString();
HttpContext.Current.Response.Redirect(redi.ToString());
}
}
I also tried adding this above it (a bit I used in another site for a similar problem):
// Wait until page is copletely loaded before sending anything since we re-build
HttpContext.Current.Response.BufferOutput = true;
I am using c# in .NET 3.5 on IIS 6.
Chad,
Did you try ending the output when you redirect? There is a second parameter that you'd set to true to tell the output to stop when the redirect header is issued. Or, if you are buffering the output then maybe you need to clear the buffer before doing the redirect so the headers are not sent out along with the redirect header.
Brian
This error usually means that something has bee written to the response stream before a redirection is initiated. So you should make sure that the test for https is done fairly high up in the page load function.