Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将HttpWebRequest与动态URI一起使用会导致;参数无效";在Image.FromStream中_C#_Url_Dynamic_Httpwebrequest - Fatal编程技术网

C# 将HttpWebRequest与动态URI一起使用会导致;参数无效";在Image.FromStream中

C# 将HttpWebRequest与动态URI一起使用会导致;参数无效";在Image.FromStream中,c#,url,dynamic,httpwebrequest,C#,Url,Dynamic,Httpwebrequest,我正在尝试获取一个图像以编码到WordML文档。这个函数的原始版本使用了文件,但我需要对其进行更改,以便使用aspx页面动态创建图像。我已经修改了代码以使用HttpWebRequest而不是WebClient。问题是我认为页面请求没有得到解决,因此图像流无效,在调用image.FromStream时生成错误“parameter is not valid” public string RenderCitationTableImage(string citation_table_id) {

我正在尝试获取一个图像以编码到WordML文档。这个函数的原始版本使用了文件,但我需要对其进行更改,以便使用aspx页面动态创建图像。我已经修改了代码以使用HttpWebRequest而不是WebClient。问题是我认为页面请求没有得到解决,因此图像流无效,在调用image.FromStream时生成错误“parameter is not valid”

    public string RenderCitationTableImage(string citation_table_id)
{
    string image_content = "";
    string _strBaseURL = String.Format("http://{0}",
        HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped));
    string _strPageURL = String.Format("{0}{1}", _strBaseURL,
        ResolveUrl("~/Publication/render_citation_chart.aspx"));

    string _staticURL = String.Format("{0}{1}", _strBaseURL,
        ResolveUrl("~/Images/table.gif"));

    string _fullURL = String.Format("{0}?publication_id={1}&citation_table_layout_id={2}",
                                        _strPageURL, publication_id, citation_table_id);


    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_fullURL);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream image_stream = response.GetResponseStream();
        // Read the image data
        MemoryStream ms = new MemoryStream();
        int num_read;
        byte[] crlf = System.Text.Encoding.Default.GetBytes("\r\n");
        byte[] buffer = new byte[1024];
        for (num_read = image_stream.Read(buffer, 0, 1024); num_read > 0; num_read = image_stream.Read(buffer, 0, 1024))
        {
            ms.Write(buffer, 0, num_read);
        }

        // Base 64 Encode the image data
        byte[] image_bytes = ms.ToArray();
        string encodedImage = Convert.ToBase64String(image_bytes);
        ms.Position = 0;
        System.Drawing.Image image_original = System.Drawing.Image.FromStream(ms); // <---error here: parameter is not valid
        image_stream.Close();

        image_content = string.Format("<w:p>{4}<w:r><w:pict><w:binData w:name=\"wordml://{0}\">{1}</w:binData>" +
            "<v:shape style=\"width:{2}px;height:{3}px\">" +
            "<v:imagedata src=\"wordml://{0}\"/>" +
            "</v:shape>" +
            "</w:pict></w:r></w:p>", _word_image_id, encodedImage, 800, 400, alignment.center);

        image_content = "<w:br w:type=\"text-wrapping\"/>" + image_content + "<w:br w:type=\"text-wrapping\"/>";
    }
    catch (Exception ex) 
    {
        return ex.ToString();
    }
    return image_content;
公共字符串RenderStationTableImage(字符串引用\u表\u id)
{
字符串图像_content=“”;
string _strBaseURL=string.Format(“http://{0}”,
HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort,UriFormat.Unescaped));
string _strPageURL=string.Format(“{0}{1}”,_strBaseURL,
ResolveUrl(“~/Publication/render_引文_chart.aspx”);
string _staticURL=string.Format(“{0}{1}”,_strBaseURL,
ResolveUrl(“~/Images/table.gif”);
string _fullURL=string.Format(“{0}?出版物_id={1}&引文_表格_布局_id={2}”,
_strPageURL、出版物id、引文表格id);
尝试
{
HttpWebRequest请求=(HttpWebRequest)WebRequest.Create(_fullURL);
HttpWebResponse=(HttpWebResponse)request.GetResponse();
Stream image_Stream=response.GetResponseStream();
//读取图像数据
MemoryStream ms=新的MemoryStream();
int num_read;
byte[]crlf=System.Text.Encoding.Default.GetBytes(“\r\n”);
字节[]缓冲区=新字节[1024];
对于(num_read=image_stream.read(缓冲区,0,1024);num_read>0;num_read=image_stream.read(缓冲区,0,1024))
{
ms.Write(缓冲区,0,num_读取);
}
//Base 64对图像数据进行编码
byte[]image_bytes=ms.ToArray();
string encodedImage=Convert.tobase64字符串(图像字节);
ms.Position=0;

System.Drawing.Image_original=System.Drawing.Image.FromStream(ms);//更新:

请阅读更新后的问题。由于您遇到登录问题,请在执行请求之前尝试执行以下操作:

request.Credentials = CredentialCache.DefaultCredentials
如果这不起作用,那么问题可能是身份验证不是在静态文件上强制执行的,而是在动态文件上强制执行的。在这种情况下,您需要先登录(使用客户端代码)并保留登录cookie(在登录请求和第二个请求上使用)或者关闭您试图访问的页面上的身份验证

原件:

由于它与一个HTTP URL一起工作,而与另一个URL不工作,因此开始诊断这一问题的地方是在HTTP级别找出两个请求之间的差异,这说明了代码中行为的差异

为了找出区别,我使用Fiddler()来比较这两个请求。比较HTTP头。它们是相同的吗?特别是,它们是相同的HTTP内容类型吗?如果不是,这可能是问题的根源

如果标题相同,请确保静态图像和动态图像在服务器上的内容和文件类型完全相同。(例如,使用文件…另存为将浏览器中的图像保存到磁盘)。然后使用Fiddler的十六进制视图来比较图像内容。您是否看到任何明显的差异


最后,我相信您已经检查过了,但只是要确保:
/Publication/render\u引文\u chart.aspx
指的是一个实际的图像文件,而不是IMG元素周围的HTML包装,对吗?这可以解释您看到的行为,浏览器呈现图像正常,但您的代码不正常。

所以您的
静态URL
指的是GIF格式的文件。
fullURL
指的是什么?可能不是有效的图像格式?返回的错误是什么?是否确定HttpWebRequest使用的Url与您在浏览器中粘贴的Url完全相同?请尝试使用HttpWebRequest应用程序()获取tracelog然后看看它说了些什么。使用StreamReader,我能够确定响应中包含的内容是用户的默认登录页面。看起来像是某种权限问题,但我认为WebRequests会使用已登录用户提供的权限?有人对此有见解吗?请参阅我的上文注释。我将返回登录页面而不是图像。是的,有意义。请参阅我的更新答案--这是否解决了问题?是的!一位同事向我指出了另一个解决问题的项目中的类似片段。答案是包含当前请求对象的CookieContainer。CookieContainer myContainer=new CookieContainer();for(int i=0;i<\u currentRequest.Cookies.Count;i++){HttpCookie http\u cookie=\u currentRequest.Cookies[i];cookie cookie cookie=new cookie(http\u cookie.Name,http\u cookie.Value,http\u cookie.Path);myContainer.Add(new Uri(\u currentRequest.Url.ToString()),cookie);}//创建web请求并获取响应HttpWebRequest请求=(HttpWebRequest)WebRequest.create(_fullURL);request.CookieContainer=myContainer;