简体   繁体   中英

HTTP Error 404.0 Not Found - when opening files that contain “#” character

Cannot open .PDF files that contain sharp (#) characters on browser. Example: Visual C# How to Program.pdf.

Code to download book:

<asp:FormView ID="FormView2" runat="server">
            <ItemTemplate>
                <asp:LoginView ID="LoginView1" runat="server">
                    <LoggedInTemplate>
                            <asp:HyperLink ID="HyperLink1" ToolTip="Download book" runat="server" NavigateUrl='<%# Eval("PDFUrl") %>' Text="Download" Target="_blank"></asp:HyperLink>
                        <br />
                    </LoggedInTemplate>
                    <AnonymousTemplate>
                        <asp:LoginStatus ID="LoginStatus1" LoginText="Login" runat="server" /> or <a href="../login/register.aspx">register</a> to download book.
                    </AnonymousTemplate>
                </asp:LoginView>
            </ItemTemplate>
        </asp:FormView>

When I click Download, on the new tab it shows:

HTTP Error 404.0 - Not Found The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

That is because a # has a special meaning in urls. It marks the begin of the hash, usually used to define the anchor in the page where to go to.

You can escape the hash by using %23 instead.

The easiest way to do that is to call UrlEncode :

HttpUtility.UrlEncode((string)Eval("PDFUrl"))

# is a reserved character in the URL specification, so I imagine the URL actually being received by the browser doesn't contain:

Visual C# How to Program.pdf

but instead just contains:

Visual C

(Since anything after a hash character is for client-side navigation, I don't think it's even sent to the server.) Hence the 404 error.

You need to URL-encode your values. It's been a while since I've used WebForms, but this might work:

NavigateUrl='<%# HttpContext.Current.Server.UrlEncode(Eval("PDFUrl")) %>'

Whether or not this works directly in the binding on the page markup, the point remains that you need to URL-encode your URLs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM