Web Api返回文本文件的垃圾,除非从浏览器栏运行 [英] Web Api returns garbage for text files unless run from the browser bar

查看:180
本文介绍了Web Api返回文本文件的垃圾,除非从浏览器栏运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Asp.Net的Web Api编写文件服务。该服务从SQL Server中检索文件(Css,Excel,Csv等),并为响应Get请求提供服务。



我的第一个测试用例是针对Css文件。问题是,虽然我可以在服务器端看到正确的数据,但是当浏览器检索/解码它时,结果就会被破坏。这个问题似乎与编码有关。



以下是FireFox中的请求/响应标头:





当我点击FireBug中的响应标签,这是它的样子:





结果看起来像ascii显示为utf8。这是FireBug中的html视图:





上面的例子是运行ssl的Facebook应用程序中的iFrame。



如果我拿起URL并直接在浏览器中打开它,它可以正常显示我的Css:





总之,当我从我的Facebook应用程序中的标签中检索到我的Css文件时,我收到垃圾编码问题?)。如果我从浏览器中直接找回它,它可以工作。



我的CssFormatter MediaTypeFormatter代码:

公开覆盖任务WriteToStreamAsync(Type type,object value,Stream writeStream,HttpContent content,TransportContext transportContext)
{

var taskSource = new TaskCompletionSource< object>();
try
{
var incomingFile = value as FileRestService.Entity.IFile;

var ms = new MemoryStream(incomingFile.DataBuffer);

ms.CopyTo(writeStream);
ms.Flush();

taskSource.SetResult(writeStream);

}
catch(异常e)
{
taskSource.SetException(e);
}
return taskSource.Task;

}

我是否错误地创建回应流?我注意到响应标头没有指定编码。这是一个问题吗?

解决方案

我找到最简单的方法来处理这个是沿着(这里是重要的)详细信息):

  public class Formatter:MediaTypeFormatter {
// TODO覆盖构造函数以添加一些映射或其他一些方式为这个格式化程序被拿起

// TODO根据你的规则覆盖CanReadType和CanWriteType

public override void SetDefaultContentHeaders(Type t,HttpContentHeaders headers,string mediaType){
base.SetDefaultContentHeaders(t,headers,mediaType);
headers.ContentDisposition = new ContentDispositionHeaderValue(attachment){
FileName =SomeName.ext
};
}

public override任务WriteToStreamAsync(键入t,对象值,Stream s,HttpContentHeaders标头,TransportContext上下文){
return Task.Factory.StartNew(()=> {
// TODO代码写入输出流,刷新但不显式关闭它
});
}
}


I am writing a file service using Asp.Net’s Web Api. The service retrieves files (Css, Excel, Csv, etc.) from SQL Server and serves them up in response to Get requests.

My first test case is for Css files. The issue is that, while I can see the correct data on the server side, when the browser retrieves/decodes it, the results are mangled. The issue appears to be related to the encodings.

Here are the request/response headers in FireFox:

When I click on the response tab in FireBug, here’s what it looks like:

The results look like ascii being displayed as utf8. This is the html view in FireBug:

The above example is an iFrame inside a Facebook application which is running ssl.

If I take the url and open it directly in the browser, it works and correctly displays my Css:

In summary, when I retrieve my Css file from a tag inside my Facebook app, I get garbage (encoding issue?). If I retrieve it straight from the browser, it works.

My CssFormatter MediaTypeFormatter code:

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
    {

        var taskSource = new TaskCompletionSource<object>(); 
        try
        {
            var incomingFile = value as FileRestService.Entity.IFile;

            var ms = new MemoryStream(incomingFile.DataBuffer);

            ms.CopyTo(writeStream);
            ms.Flush();

            taskSource.SetResult(writeStream);

        }
        catch (Exception e) 
        { 
            taskSource.SetException(e); 
        } 
        return taskSource.Task; 

    }

Am I creating the response stream incorrectly? I noticed that the response headers do not specify the encoding. Is this an issue?

解决方案

I find the easiest way to handle this is to write something along the lines of (here's the important details):

public class Formatter : MediaTypeFormatter {
    // TODO override the constructor to add some mappings or some other way for this formatter to be picked up

    // TODO override CanReadType and CanWriteType according to your rules

    public override void SetDefaultContentHeaders(Type t, HttpContentHeaders headers, string mediaType) {
        base.SetDefaultContentHeaders(t, headers, mediaType);
        headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
            FileName = "SomeName.ext"
        };
    }

    public override Task WriteToStreamAsync(Type t, object value, Stream s, HttpContentHeaders headers, TransportContext context) {
        return Task.Factory.StartNew(() => {
            // TODO code to write to the output stream, flush it but don't explicitly close it
        });
    }
}

这篇关于Web Api返回文本文件的垃圾,除非从浏览器栏运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆