Bryan Dellinger
Bryan Dellinger

Reputation: 5294

in razor how to have a link to an external url from the database

in my razor page I have.

<p>
    <span>Website: </span>
    <span>
        <a href="@(Url.Encode(Model.PrimaryInfo.WebsiteUrl))" target="_blank">@Model.PrimaryInfo.WebsiteUrl</a>
    </span>
</p>

when I inspect the element I see. the page displays as

Website: https://www.mywebsite.org/

when I inspect element I get

<a href="https%3a%2f%2fwww.mywebsite.org%2f" target="_blank">https://www.mywebsite.org/</a>

and when I click the link I get

[HttpException (0x80004005): A potentially dangerous Request.Path value was detected from the client (:).]
System.Web.HttpRequest.ValidateInputIfRequiredByConfig() +9939972
System.Web.PipelineStepManager.ValidateHelper(HttpContext context) +53

Upvotes: 0

Views: 1286

Answers (2)

CMoussalli
CMoussalli

Reputation: 26

Here is your checklist:

  1. Non-unicode datatype not used: validate that you are storing URLs in the database as an NVarChar type and don't use VarChar

  2. No need to encode: remove the encoding.

  3. Validate that you are not violating request validation scheme as per .Net. Please refer to hanslman article: https://www.hanselman.com/blog/ExperimentsInWackinessAllowingPercentsAnglebracketsAndOtherNaughtyThingsInTheASPNETIISRequestURL.aspx

Upvotes: 1

Talha Afzal
Talha Afzal

Reputation: 65

Try to use this

public static class LinkHelper{
public static string ExternalLink(this HtmlHelper helper, string url, string text)
    {
        return String.Format("<a href='http://{0}' target="_blank">{1}</a>", url,text);
}}

and in view

@Html.ExternalLink("www.google.com", "Google")

Upvotes: 1

Related Questions