.NET ServiceModel.Syndication - Changing Encoding on RSS Feed

假装没事ソ 提交于 2019-12-04 06:03:19

The reason this happens is because you are passing a StringBuilder to the XmlWriter constructor. Strings in .NET are unicode so XmlWriter assumes utf-16 and you cannot modify this.

So you could use a stream instead of string builder, then you can control the encoding with the settings:

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");
}

All this being said a far better, more MVCish and a one the I would recommend you solution is to write a 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);
        }
    }
}

and in your controller action simply return this result so that you don't clutter your controller actions with plumbing code:

public ActionResult Index()
{
    var ideas = _repository.GetIdeas(0, 15).Ideas;
    var feed = _syndication.SyndicateIdeas(ideas);
    return new SyndicationResult(feed);
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!