Error 400 (Bad Request) when get a file which name contains & character in C# ASP.NET MVC3 - c#

I have an issue regarding the filename which contains & character.
I have to get an image which name is: Test&TestAgain.jpg. In ASP.NET MVC3 application, in View side, I put
Url.Content( "~/Content/Images/"+ filename );
In Chrome, I see error 400 Bad Request because of filename which contains &.
I think that & is used for query string and browser interprets file name as query string.
Because filename doesn't contain ? then browser throw that error. (A potentially dangerous Request.Path value was detected from the client (&).)
It is a way (workaround) to fix this without replace that character ?

You need to UrlEncode the path:
Url.Content("~/Content/Images/" + HttpServerUtility.UrlEncode(filename));
Edit:
Seems it doesn't work. The only way I can think of right now is to allow resticted characters and enable VerificationCompatibility by setting in the registry:
// 32-bit IIS
HKLM\SOFTWARE\Microsoft\ASP.NET VerificationCompatibility = 1
// 64-bit IIS
HKLM\SOFTWARE\Wow6432Node\Microsoft\ASP.NET VerificationCompatibility = 1

Related

Japanese characters in host name for Chilkat FTP2

I went through Chilkat's forum where i see that forum is closed and I should post related question here on SO.
I am trying to connect to FTP server using FTP2 of chilkat, but it fails to connect to valid ftp server with valid credentials.
Host name does contain Japanese characters "w10jpnツ新".
My code looks like below:
Ftp2 objFtp = new Ftp2();
const string ChilkatFTPKey = ValidChilKatFTPKey;
bool success = objFtp.UnlockComponent(ChilkatFTPKey);
if (!success)
{
return;
}
objFtp.Hostname = _ftpServer;
Log.Write("Host Name Input: " + _ftpServer); //here I see "w10jpnツ新"
Log.Write("Host Name: " + objFtp.Hostname); //here I see "w10jpnツ新"
As you can see even after setting proper host name to objFtp.Hostname , that property is having garbage value and thus connection attempt fails.
How to fix it?
UPDATE
Initially this question was written to Chilkat technicians, but as now as there is no response from them, I m adding general tags to make it in reach of general people in Hope if they may know what can be possible reason behind such problem.
One thing i could think is if in setter of the property Hostname if they convert Japanese characters into something unwanted. But why would they do it.
I see the problem -- Chilkat is assuming that the Hostname is composed of Latin1 (us-ascii + accented European chars). I'll make the fix and I can provide a pre-release. Which version of the .NET Framework do you use, and which version of Visual Studio?
Also.. the objFtp.Hostname property should be set to a domain name or an IP address. The string "w10jpnツ新" is not a valid domain name. A domain name is something like "xyz.com" -- something that a DNS server can resolve to an IP address.

Directory.Exists(#"\\SERVERIP\aFolder\bFolder"); always returns false

The following path always returns false:
Directory.Exists(#"\\SERVERIP\aFolder\bFolder");
// where SERVERIP is the server-IP which is being accessed using Impersonation
After debugging the code, it places double-slashes in the Debugger.
I have accessed the above file path without the # and double-quotes in WindowsExplorer.
What am I doing wrong?
[ The code will run on a network ]
The problem might be in the paths-[Source/Destinations] (both or one of it[source/destination] might be causing the problem) due to the default-paths used by Visual-Studio. So let me explain how to check wether the paths are correct/incorrect step by step.
Configuring ** SOURCE-PATH **:
Some times this path DRIVE:\ProgramFiles\IISExpress (or some other path depending on the installation location of IIS) gets concatenated with the SOURCE-PATH you give in the input To solve this problem, follow/verify these steps:
Ensure that the SOURCE-PATH or File you are using is in the Project-Folder
To Access the SOURCE-PATH or File. Always use this path/way:
// 1. SOURCE-PATH + fileName with Extension<br>
Server.MapPath("~\FolderInsideProjectFolder\", "fileName.extension");
Configuring ** DESTINATION-PATH (to a Mapped-NETWORK) **:
This path creates a problem if the path you entered has some words mispelled OR if you don't have access to the specified Server-IP[DestinationServerIP]. To solve this problem, follow/verify these steps:
Before Accessing the DESTINATION-PATH or File , ensure that the IP-Address you are referring to is Accessible to the Account under which your Application-code is running.To learn how to run Applications under an Account. See Impersonization
To Access the DESTINATION-PATH or File. Always use this path/way:
// 2. DESTINATION-PATH + fileName with Extension
#"\\SERVERIP\aFolder\bFolder" + "fileName.extension";
NOTE:
Remember that the SOURCE-PATH can be checked if it (exists/does not exist) by addressing its Fully-Qualified-Address and in that case, it will return true if it exists (The full-path that windows-explorer shows you in the Address Bar (Windows-Explorer) like DRIVE:/....../
EXTRA-INFORMATION: (as it was the basic INTENSION)
One line instruction to Copy the file from local-system → networked-mapped drive/path is:
System.IO.File.Copy(
Server.MapPath("~\FolderInsideProjectFolder\", "fileName.extension"),
#"\\SERVERIP\aFolder\bFolder" + "fileName.extension"
[, true ] // Optional if you want the file to be over-written or not
);
Please inform, if any thing still is not cleared (but after some nice searching ☋ ☛ )
Many a times I have seen file (or directory) access problems when the user (a human, system user such as IIS_IUSR or an application) lacks required privileges.
According to this question where the asker is facing similar problem, I believe that this may help you.
Let us know, if it helps.

Hashids not working in .NET when decoding

I am using Hashids to hide database IDs in the URL. Following is my initialization of Hashids:
public static Security.Hashids HashOps = new Security.Hashids("Sl212", 5);
Security is my project's namespace inside which I copied Hashids.cs file. The encoding is working correctly but decoding is throwing IndexOutOfRangeException exception. This is how I am decoding:
int fileID=HashOps.Decode(FileID)[0];
I tried it on many salts and without salt, but its throwing the same exception again and again. I am using the original code from the file. Except namespace I changed nothing.
Please tell me what to do? After trying for 12 hours my mind is stuck at dead end.
UPDATE
A test code I am running in Console app also throwing exception:
Hashids HashOps = new Hashids();
string hash = HashOps.Encode(212);
Console.WriteLine("Encoded: " + hash);
Console.WriteLine("Decoded: " + HashOps.Decode(hash)[0]);
Finally, with the help of #Heinzi I was able to detect what was really going on. The problem was with my web application's URL detection system. Which detects the URL and loads the content in a DIV. That system was making the complete URL lower cased. Hence, changing the hash containing the capital letter. I just used the actual URL instead of lowered one when detecting IDs.

ASP.NET cookies missing in HttpContext.Request.Cookies. Comma vs semi-colon separated cookies from Chrome/IE

I'm observing an issue where I make a request to my server and inspect the HttpContext.Request.Cookies collection to be different in Chrome vs IE.
My process is as follows:
Launch a new inPrivate browser for IE, go to site url
Observe HttpContext.Request.Cookies to have three values, siteLang, siteDir, isNative
Observe the value of each cookie to respectively be:
HttpContext.Request.Cookies["siteDir"].Value == "ltr"
HttpContext.Request.Cookies["siteLang"].Value == "en-US"
HttpContext.Request.Cookies["isNative"].Value == true
Launch a new incognito browser for Chrome, go to site url
Observe HttpContext.Request.Cookies to have one value, siteDir
Observe the value of HttpContext.Request.Cookies["siteDir"].Value to be "ltr, siteLang=en-US, isNative=true"
I have also observed HttpContext.Request.Headers["Cookie"] to contain the following values dependent on browser:
siteLang=en-US; siteDir=ltr; isNative=true // IE
siteDir=ltr, siteLang=en-US, isNative=true // Chrome
So it appears Chrome is comma separating my cookies and IE is using semi-colons and Mvc can't figure out how to deal with the commas. Has anyone else seen this? I feel like this issue should be incredibly widespread if my diagnosis is correct. Any input is greatly appreciated.
EDIT
I've looked into the ASP.NET source and found the following code snippet in HttpRequest.cs (found here: [http://referencesource.microsoft.com/#System.Web/HttpRequest.cs][1]):
while (i < l) {
// find next ';' (don't look to ',' as per 91884)
j = i;
while (j < l) {
ch = s[j];
if (ch == ';')
break;
j++;
}
// create cookie form string
...{continued}
Any ideas how I get information on 91884 to understand why they are ignoring comma separated cookies?
I am noticing odd behavior like this right now too.
But looking at Fiddler, the cookie list is actually sent as ';' separated..
I am on Windows 10. I've tried rolling back my commit history to several months back but keep running into the issue.
The issue seems to especially happen on SSL. Can it be OS/WindowsUpdate related?

The ';' character, hexadecimal value 0x3B, cannot be included in a name

I have seen the error "The ';' character, hexadecimal value 0x3B, cannot be included in a name." in my log files for an ASP.NET Web App. The url that's logged looks something like this:
mypage.aspx?paramone=one+two&paramtwo=zero+1
So my first question is what type of system/browser is encoding the original query string? (This happens rarely)
I've tried to address this problem with the following snippet of code in the Page_Load() event:
string rawUrl = Request.RawUrl;
if (rawUrl.Contains(amp))
{
rawUrl = rawUrl.Replace("&", "&");
Server.Transfer(rawUrl, false);
return;
}
However when it transfers back to this page the & is back in the query string. So I'm guessing that the .Transfer() function encodes the first param.
Suggestions about solving this problem?
Your web server should be able to log the "user agent" field from the HTTP Request, which should enable you to identify the culprit.
Don't fix it - there's a very well defined set of legal syntaxes for URI parameters, and this ain't one of them.
When you try to export a Microsoft catalog to XML, the resulting file cannot be imported, and you receive the following error message
"The XML file path/filename contains an error at line. " "A Name contained an invalid character."
If you validate the XML catalog by using Microsoft Visual Studio .NET you receive the following error message:
"The '(' character, hexadecimal value 0x28, cannot begin a name. Line #, Position #"
This problem occurs because the Commerce Server export was not encoding the following special characters:
The range 0x0021 – 0x002F includes ! “ # $ % & ‘ ( ) * + , - . /
The range 0x03A – 0x0040 includes : ; < = > ? #
The range 0x007B – 0x007E includes { | } ~
The range 0x005B – 0x005E [ \ ] ^**

Categories