我昨天升级到了MVC 4,刚刚发现了升级引入的错误。
我有一个Razor视图,用于生成RSS提要。它有一些这样的标记(简化):
<item>
<title>@post.BlogPost.Title</title>
<link>@Url.BlogPost(post.BlogPost, isAbsolute: true)</link>
</item>
在Razor第二版中,special support为HTML5 void elements。这种虚空元素是自动关闭的,没有结束标记。
不幸的是,<link>
就是这样一个元素。
这意味着上面的Razor标记不再有效,并且在运行时失败。删除结束</link>
标记会删除解析器错误,但意味着它不再是有效的RSS。
那么,有没有办法解决这个问题,或者Razor是否真的适合生成HTML5?
答案 0 :(得分:11)
我会这样做:
<item>
<title>
@post.BlogPost.Title
</title>
@Html.Raw("<link>")
@Url.BlogPost(post.BlogPost, isAbsolute: true)
@Html.Raw("</link>")
</item>
生成的源代码如下:
<item>
<title>
Google
</title>
<link>
http://www.google.se
</link>
</item>
答案 1 :(得分:2)
现在我采用这种解决方法:
@Html.Raw(string.Format(@"<param name=""{0}"">{1}</param>",Name, Value))
答案 2 :(得分:2)
由于亚历山大·塔兰(Alexander Taran)在寻找这个问题的确切答案时已经开启了这个问题的赏金,我想我会查看Razor source code on CodePlex并提供一些细节。
首先,看看HtmlMarkupParser
。它包含此参考数据:
//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"
};
这是通过HtmlMarkupParser.VoidElements
公开的,此属性的唯一用途是HtmlMarkupParser.RestOfTag(...)
。这是一个遍历一系列标记的解析器。相关的代码片段是:
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();
}
这意味着将成功解析以下内容:
<link></link>
然而,前瞻是有限的,这意味着在结束标记之前看到的任何额外令牌都会导致它失败:
<link>Some other tokens</link>
在这种情况下,可以延长前瞻的范围。如果有人热衷于此,他们可以向MVC团队提供拉取请求。
答案 3 :(得分:1)
Html5链接是样式表等标题中使用的特殊元素。
你的Rss不应该是Html5,而是
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
你可以在你的RSS源使用
的布局控制器中使用它<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
@RenderBody()
</rss>
我已经做过的另一种方法是拥有一个完全空的视图,然后是下面的控制器:
[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);
}
特别值得注意的是System.ServiceModel.Syndication.SyndicationFeed
这是我的自定义结果
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);
}
}
}
答案 4 :(得分:1)
对这个问题的简短回答似乎是,Razor与第2版一样,与HTML有关,而不是XML。我asked one of the dev's for confirmation,所以希望他能回来。
我最终改变了我的方法,将Linq用于XML和自定义ActionResult
,绕过了Razor,甚至是任何视图引擎:
[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;
}
这需要以下自定义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);
}
}
答案 5 :(得分:0)
你可以做的是:
@("<link>" + Url.BlogPost(post.BlogPost, isAbsolute: true) + "</link>")
更简单