I have a following Razor component (Blazor serverside?) in ASP.Core 3.0 razor pages (normal) project:
@using WEKA.Models
@using Microsoft.AspNetCore.Html
<div class="jobs-list">
@foreach (var e in News)
{
<div class="job" data-aos="fade-up">
<a href="@e.Link">
<div class="col name">@e.Text)</div>
<div class="col more">Detail</div>
</a>
</div>
}
</div>
@code {
public List<QNewsList> News
{
set { }
get
{
using (WEKAContext db = new WEKAContext())
{
var q = from n in db.Qaktuality select new QNewsList() { Datum = n.Datum.ToString("d.M.YYYY"), Text = new HtmlString(n.Text), Link = n.RssLink };
return q.ToList();
}
}
}
public class QNewsList
{
public string Datum;
public HtmlString Text;
public string Link;
}
}
The component is rendered in a normal cshtml razor page:
@(await Html.RenderComponentAsync<WEKA.Components.NewsList>(RenderMode.Static))
I am trying to make the database field Text
appear on the web page as raw HTML (i.e. rendering
as a space). The Html
object is not available here to call Html.Raw
.
This code above does not render raw html from database. How can I fix it?
Raw can result in a XSS vulnerability being exploitable since an attacker can craft a special URL containing a malicious JavaScript payload that will be executed by the victim's browser if he or she sends an invalid 2FA confirmation code.
Raw HTML can be rendered in Blazor by using the MarkupString. You can set the raw HTML as a string to any parameter and cast it in a markup string.
Using Html. Raw allows you to output text containing html elements to the client, and have them still be rendered as such. Should be used with caution, as it exposes you to cross site scripting vulnerabilities.
See the doc here and from what @Hrnk has said, you need to use MarkupString
instead of HtmlString
in razor component.Change code to below
@using WEKA.Models
@using Microsoft.AspNetCore.Html
<div class="jobs-list">
@foreach (var e in News)
{
<div class="job" data-aos="fade-up">
<a href="@e.Link">
<div class="col name">@e.Text</div>
<div class="col more">Detail</div>
</a>
</div>
}
</div>
@code {
public List<QNewsList> News
{
set { }
get
{
using (WEKAContext db = new WEKAContext())
{
var q = from n in db.Qaktuality select new QNewsList() { Datum = n.Datum.ToString("d.M.YYYY"), Text = new MarkupString(n.Text), Link = n.RssLink };
return q.ToList();
}
}
}
public class QNewsList
{
public string Datum;
public MarkupString Text;
public string Link;
}
}
Refer to https://github.com/aspnet/Blazor/issues/167
https://github.com/aspnet/AspNetCore/issues/12615
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With