实现System.Web.Http.WebHost.WebHostBufferPolicySelector.IHostBufferPolicySelector

DaN*_*Net 3 c#-4.0 asp.net-web-api

我想下面如何上传使用通过Asp.Net Web窗体在Web API类大文件网络博客.如果你查看帖子,你会注意到为了避免因为缓冲大文件而导致内存不足,他们建议覆盖IHostBufferPolicySelector接口.我在哪里实现界面?我是在Web Api类中,在Global.asax中进行的,还是完全偏离轨道并需要在其他地方执行?

Fil*_*p W 5

您不需要实现此接口,我只将其列为参考 - 该代码已经是Web API源代码的一部分(下System.Web.Http/Hosting/IHostBufferPolicySelector.cs)

您需要做的是覆盖基类 System.Web.Http.WebHost.WebHostBufferPolicySelector

这就够了:

public class NoBufferPolicySelector : WebHostBufferPolicySelector
{
   public override bool UseBufferedInputStream(object hostContext)
   {
      var context = hostContext as HttpContextBase;

      if (context != null)
      {
         if (string.Equals(context.Request.RequestContext.RouteData.Values["controller"].ToString(), "uploading", StringComparison.InvariantCultureIgnoreCase))
            return false;
      }

      return true;
   }

   public override bool UseBufferedOutputStream(HttpResponseMessage response)
   {
      return base.UseBufferedOutputStream(response);
   }
}
Run Code Online (Sandbox Code Playgroud)

然后在任何一个Global.asaxWebApiConfig.cs(以您喜欢的任何一个)注册您的新课程:

GlobalConfiguration.Configuration.Services.Replace(typeof(IHostBufferPolicySelector), new NoBufferPolicySelector());
Run Code Online (Sandbox Code Playgroud)