我正试图解决一个错误,在http://captainobvio.us中,我正在生成的所有RSS提要都会在Internet (版本8和9)中产生以下错误:
不支持从当前编码切换到指定编码的
源代码错误切换。行:1字符: 40
问题是,通过HTTP报头发送的实际编码类型与文档声明的不同。下面是我的代码,用于将提要的输出写入HTML:
public ContentResult Index()
{
var feed = _syndication.SyndicateIdeas(_repository.GetIdeas(0,15).Ideas);
var sb = new StringBuilder();
using (var writer = XmlWriter.Create(sb, new XmlWriterSettings { Encoding = Encoding.UTF8, NewLineHandling = NewLineHandling.Entitize, NewLineOnAttributes = true, Indent = true}))
{
feed.SaveAsRss20(writer);
writer.Close();
}
return Content(sb.ToString(), "application/rss+xml", Encoding.UTF8);
} 下面是使用System.ServiceModel.Syndication在.NET 4.0中实际构建提要的代码:
var feed = new SyndicationFeed("CaptainObvio.us - Recent Ideas",
"The most recent ideas posted by the Community on CaptainObvio.us", new Uri("http://captainobvio.us/"), "CaptainObvio.us", new DateTimeOffset(ideas[0].DatePosted), items)
{
Generator = "CaptainObvio.us - http://captainobvio.us/"
};
return feed;我想要做的是将XML文档改为utf-8,而不是utf-16。我还检查了编码命名空间,以确定是否有UTF16选项(这样我就可以更正header而不是XML ),但是找不到。
是否有一种简单的方法直接从System.ServiceModel.Syndication更改XML文档上的编码属性?解决这个问题最简单的方法是什么?
发布于 2011-03-28 06:30:50
之所以会发生这种情况,是因为您要将一个StringBuilder传递给XmlWriter构造函数。.NET中的字符串是unicode,因此XmlWriter假设utf-16,您不能修改它。
因此,您可以使用流而不是字符串生成器,然后可以使用以下设置来控制编码:
var settings = new XmlWriterSettings
{
Encoding = Encoding.UTF8,
NewLineHandling = NewLineHandling.Entitize,
NewLineOnAttributes = true,
Indent = true
};
using (var stream = new MemoryStream())
using (var writer = XmlWriter.Create(stream, settings))
{
feed.SaveAsRss20(writer);
writer.Flush();
return File(stream.ToArray(), "application/rss+xml; charset=utf-8");
}所有这一切--更好的、更多的MVCish --以及我推荐的解决方案是编写一个SyndicationResult
public class SyndicationResult : ActionResult
{
private readonly SyndicationFeed _feed;
public SyndicationResult(SyndicationFeed feed)
{
if (feed == null)
{
throw new HttpException(401, "Not found");
}
_feed = feed;
}
public override void ExecuteResult(ControllerContext context)
{
var settings = new XmlWriterSettings
{
Encoding = Encoding.UTF8,
NewLineHandling = NewLineHandling.Entitize,
NewLineOnAttributes = true,
Indent = true
};
var response = context.HttpContext.Response;
response.ContentType = "application/rss+xml; charset=utf-8";
using (var writer = XmlWriter.Create(response.OutputStream, settings))
{
_feed.SaveAsRss20(writer);
}
}
}在控制器操作中,只需返回此结果,这样就不会将控制器操作与管道代码混淆:
public ActionResult Index()
{
var ideas = _repository.GetIdeas(0, 15).Ideas;
var feed = _syndication.SyndicateIdeas(ideas);
return new SyndicationResult(feed);
} https://stackoverflow.com/questions/5452878
复制相似问题