Using Razor 2 to write RSS fails on the <link> element
-
13-12-2019 - |
Question
I upgraded to MVC 4 yesterday and just discovered a bug that the upgrade introduced.
I have a Razor view that is used to generate an RSS feed. It has some markup like this (simplified):
<item>
<title>@post.BlogPost.Title</title>
<link>@Url.BlogPost(post.BlogPost, isAbsolute: true)</link>
</item>
In Razor version two, there's special support for HTML5 void elements. Such void elements are self closing, and do not have a closing tag.
Unfortunately, <link>
is one such element.
This means the above Razor markup is no longer valid, and fails at runtime. Removing the closing </link>
tag removes the parser error, but means that it's no longer valid RSS.
So, is there a way to get around this, or is Razor only really suitable for generating HTML5?
Solution 4
The short answer to this question seems to be that Razor, as over version 2, is tied to HTML to the exclusion of XML. I asked one of the dev's for confirmation, so hopefully he gets back.
I ended up changing my method to use Linq to XML and a custom ActionResult
, bypassing Razor and indeed any view engine:
[HttpGet]
[OutputCache(Duration = 300)]
public ActionResult Feed()
{
var result = new XmlActionResult(
new XDocument(
new XElement("rss",
new XAttribute("version", "2.0"),
new XElement("channel",
new XElement("title", "My Blog")
// snip
)
)
)
);
result.MimeType = "application/rss+xml";
return result;
}
This requires the following custom ActionResult
:
public sealed class XmlActionResult : ActionResult
{
private readonly XDocument _document;
public Formatting Formatting { get; set; }
public string MimeType { get; set; }
public XmlActionResult([NotNull] XDocument document)
{
if (document == null)
throw new ArgumentNullException("document");
_document = document;
// Default values
MimeType = "text/xml";
Formatting = Formatting.None;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Clear();
context.HttpContext.Response.ContentType = MimeType;
using (var writer = new XmlTextWriter(context.HttpContext.Response.OutputStream, Encoding.UTF8) { Formatting = Formatting })
_document.WriteTo(writer);
}
}
OTHER TIPS
I'd do it like this:
<item>
<title>
@post.BlogPost.Title
</title>
@Html.Raw("<link>")
@Url.BlogPost(post.BlogPost, isAbsolute: true)
@Html.Raw("</link>")
</item>
Generated source will look like this:
<item>
<title>
Google
</title>
<link>
http://www.google.se
</link>
</item>
For now I go with this workaround:
@Html.Raw(string.Format(@"<param name=""{0}"">{1}</param>",Name, Value))
Since Alexander Taran has opened a bounty on this question in a search for a definitive answer to this, I thought I'd check out the Razor source code on CodePlex and provide some detail.
Firstly, take a look at HtmlMarkupParser
. It contains this reference data:
//From http://dev.w3.org/html5/spec/Overview.html#elements-0
private ISet<string> _voidElements = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen",
"link", "meta", "param", "source", "track", "wbr"
};
This is exposed via HtmlMarkupParser.VoidElements
, and the only usage of this property is in HtmlMarkupParser.RestOfTag(...)
. This is a parser that's walking through a sequence of tokens. The relevant snippet of code is:
if (VoidElements.Contains(tagName))
{
// Technically, void elements like "meta" are not allowed to have end tags. Just in case they do,
// we need to look ahead at the next set of tokens. If we see "<", "/", tag name, accept it and the ">" following it
// Place a bookmark
int bookmark = CurrentLocation.AbsoluteIndex;
// Skip whitespace
IEnumerable<HtmlSymbol> ws = ReadWhile(IsSpacingToken(includeNewLines: true));
// Open Angle
if (At(HtmlSymbolType.OpenAngle) && NextIs(HtmlSymbolType.Solidus))
{
HtmlSymbol openAngle = CurrentSymbol;
NextToken();
Assert(HtmlSymbolType.Solidus);
HtmlSymbol solidus = CurrentSymbol;
NextToken();
if (At(HtmlSymbolType.Text) && String.Equals(CurrentSymbol.Content, tagName, StringComparison.OrdinalIgnoreCase))
{
// Accept up to here
Accept(ws);
Accept(openAngle);
Accept(solidus);
AcceptAndMoveNext();
// Accept to '>', '<' or EOF
AcceptUntil(HtmlSymbolType.CloseAngle, HtmlSymbolType.OpenAngle);
// Accept the '>' if we saw it. And if we do see it, we're complete
return Optional(HtmlSymbolType.CloseAngle);
} // At(HtmlSymbolType.Text) && String.Equals(CurrentSymbol.Content, tagName, StringComparison.OrdinalIgnoreCase)
} // At(HtmlSymbolType.OpenAngle) && NextIs(HtmlSymbolType.Solidus)
// Go back to the bookmark and just finish this tag at the close angle
Context.Source.Position = bookmark;
NextToken();
}
This means that the following will be parsed successfully:
<link></link>
However the lookahead is limited, meaning that any extra tokens seen before the closing tag cause it to fail:
<link>Some other tokens</link>
It may be possible to extend the reach of the lookahead in this case. If anyone is keen, they can provide a pull request to the MVC team.
Html5 link is a special element used in header for stylesheets and the like.
Your Rss should not be Html5 but something like
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
you could have this in a layout controller that your rss feeds would use
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
@RenderBody()
</rss>
An alternative way I've done it previosly is to have a completely empty view and then the controller below:
[NHibernateActionFilter]
public AtomActionResult Feed()
{
var dto = _service.GetThings(NHibernateSession);
var items = Mapper.Map<List<ThingDto>, List<SyndicationItem>>(dto);
var url = HttpContextWrapper.Request.UrlReferrer;
var feed = new SyndicationFeed("MyTitle", "MyByline", url, items)
{
Copyright = new TextSyndicationContent("© 2012 SO"),
Language = "en-IE"
};
return new AtomActionResult(feed);
}
Of particular note is System.ServiceModel.Syndication.SyndicationFeed
And this is my custom result
public class AtomActionResult : ActionResult
{
readonly SyndicationFeed _feed;
public AtomActionResult() { }
public AtomActionResult(SyndicationFeed feed)
{
_feed = feed;
}
public override void ExecuteResult(ControllerContext context)
{
//context.HttpContext.Response.ContentType = "application/atom+xml";
//chrome does not yet support atom+xml
//http://code.google.com/p/chromium/issues/detail?id=104358
context.HttpContext.Response.ContentType = "application/xml";
var formatter = new Atom10FeedFormatter(_feed);
using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Output))
{
formatter.WriteTo(writer);
}
}
}
What you can do is this:
@("<link>" + Url.BlogPost(post.BlogPost, isAbsolute: true) + "</link>")
much simpler