如何实例化一个HttpPostedFile [英] How to instantiate a HttpPostedFile

查看:186
本文介绍了如何实例化一个HttpPostedFile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想与我无法控制的系统进行通信,但是它的一个方法接受一个HttpPostedFile是在我的代码我有一个字节数组。是否有人有实例化一个HttpPostedFile的例子,因为我知道它的构造是内部

I'm trying to communicate with a system which I have no control over, however one of it's methods takes in a HttpPostedFile were in my code I have a byte array. Does anybody have an example of instantiating a HttpPostedFile as I know it's constructor is internal?

我发现最好的是的这个SO帖子它使用反射但他们把车开进这是因为我无法改变我不能接受另一个方向第三方系统的方法签名。

The best I've found is this SO post which uses reflection however they were steered into another direction which I can't take because I am unable to modify the third party systems method signature.

推荐答案

这是真的哈克代码,但以下似乎为我工作:

This is really really hacky code, but the following seems to work for me:

public HttpPostedFile ConstructHttpPostedFile(byte[] data, string filename, string contentType) {
  // Get the System.Web assembly reference
  Assembly systemWebAssembly = typeof (HttpPostedFileBase).Assembly;
  // Get the types of the two internal types we need
  Type typeHttpRawUploadedContent = systemWebAssembly.GetType("System.Web.HttpRawUploadedContent");
  Type typeHttpInputStream = systemWebAssembly.GetType("System.Web.HttpInputStream");

  // Prepare the signatures of the constructors we want.
  Type[] uploadedParams = { typeof(int), typeof(int) };
  Type[] streamParams = {typeHttpRawUploadedContent, typeof (int), typeof (int)};
  Type[] parameters = { typeof(string), typeof(string), typeHttpInputStream };

  // Create an HttpRawUploadedContent instance
  object uploadedContent = typeHttpRawUploadedContent
    .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, uploadedParams, null)
    .Invoke(new object[]{data.Length, data.Length});

  // Call the AddBytes method
  typeHttpRawUploadedContent
    .GetMethod("AddBytes", BindingFlags.NonPublic | BindingFlags.Instance)
    .Invoke(uploadedContent, new object[] {data, 0, data.Length});

  // This is necessary if you will be using the returned content (ie to Save)
  typeHttpRawUploadedContent
    .GetMethod("DoneAddingBytes", BindingFlags.NonPublic | BindingFlags.Instance)
    .Invoke(uploadedContent, null);

  // Create an HttpInputStream instance
  object stream = (Stream)typeHttpInputStream
    .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, streamParams, null)
    .Invoke(new object[] {uploadedContent, 0, data.Length});

  // Create an HttpPostedFile instance
  HttpPostedFile postedFile = (HttpPostedFile)typeof(HttpPostedFile)
    .GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, parameters, null)
    .Invoke(new object[] {filename, contentType, stream});

  return postedFile;
}

这篇关于如何实例化一个HttpPostedFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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