我有一个自托管的Web Api控制台应用。我有它提供HTML。在HTML页面中有一个指向图像的链接(图像在编译时是已知的)。我已经尝试并且未能编写控制器方法来检索图像并将其发送到html页面。见下文。我的图像存储为链接资源。
public class ResourceFilesController : ApiController
{
public HttpResponseMessage Get()
{
Stream dataStream =
System.Reflection.Assembly.GetEntryAssembly().
GetManifestResourceStream("Properties.Resources.img2");
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
//Get argumentNull exception on this line
response.Content = new StreamContent(dataStream);
return response;
}
}
答案 0 :(得分:0)
dataStream很可能是null ..在这种情况下,webapi没有任何问题。
这是StreamContent构造函数(反编译)
public StreamContent(Stream content, int bufferSize)
{
if (content == null)
throw new ArgumentNullException("content");
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException("bufferSize");
this.content = content;
this.bufferSize = bufferSize;
if (content.CanSeek)
this.start = content.Position;
if (!Logging.On)
return;
Logging.Associate(Logging.Http, (object) this, (object) content);
}
因此,除非某些属性设置器抛出ArgumentNull异常或Logging.Associate,否则您将null传递给此构造函数
答案 1 :(得分:0)
终于搞清楚了。如果其他人有这个问题,请参阅下面的内容(似乎无法忍受的努力,你必须只是为了提供内容 - 但那个ASP.NET适合你。)
public class PageResourcesController : ApiController
{
public HttpResponseMessage Get()
{
String resourceName = "img2";
String projectName = "Owin_Test1";
ResourceManager rm = new ResourceManager(
projectName + ".Properties.Resources",
typeof(Properties.Resources).Assembly);
Object resource = rm.GetObject(resourceName);
ImageConverter imageConverter = new ImageConverter();
byte[] resourceByteArray = (byte[])imageConverter.ConvertTo(resource, typeof(byte[]));
MemoryStream dataStream = new MemoryStream(resourceByteArray);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(dataStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
return response;
}
}