我正在使用 WCF4.0 模板 -REST。我正在尝试创建一种使用流上传文件的方法。
问题总是发生在
Stream serverStream = request.GetRequestStream();
流式传输类:
namespace LogicClass
{
public class StreamClass : IStreamClass
{
public bool UploadFile(string filename, Stream fileStream)
{
try
{
FileStream fileToupload = new FileStream(filename, FileMode.Create);
byte[] bytearray = new byte[10000];
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);
totalBytesRead += bytesRead;
} while (bytesRead > 0);
fileToupload.Write(bytearray, 0, bytearray.Length);
fileToupload.Close();
fileToupload.Dispose();
}
catch (Exception ex) { throw new Exception(ex.Message); }
return true;
}
}
}
REST 项目:
[WebInvoke(UriTemplate = "AddStream/{filename}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)]
public bool AddStream(string filename, System.IO.Stream fileStream)
{
LogicClass.FileComponent rest = new LogicClass.FileComponent();
return rest.AddStream(filename, fileStream);
}
Windows 窗体项目:用于测试
private void button24_Click(object sender, EventArgs e)
{
byte[] fileStream;
using (FileStream fs = new FileStream("E:\stream.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
fileStream = new byte[fs.Length];
fs.Read(fileStream, 0, (int)fs.Length);
fs.Close();
fs.Dispose();
}
string baseAddress = "http://localhost:3446/File/AddStream/stream.txt";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseAddress);
request.Method = "POST";
request.ContentType = "text/plain";
Stream serverStream = request.GetRequestStream();
serverStream.Write(fileStream, 0, fileStream.Length);
serverStream.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
int statusCode = (int)response.StatusCode;
StreamReader reader = new StreamReader(response.GetResponseStream());
}
}
我已关闭防火墙和 Internet 连接,但错误仍然存在。有没有更好的方法来测试上传方法?
堆栈跟踪:
在 System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress 套接字地址) 在 System.Net.ServicePoint.ConnectSocketInternal(布尔 connectFailure、Socket s4、Socket s6、Socket& 套接字、IPAddress& 地址、ConnectSocketState 状态、IAsyncResult asyncResult、Int32 超时、Exception& 异常)
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您不必重新启动电脑。而是重新启动 IIS。
“主动拒绝”意味着当您尝试连接时主机发送了重置而不是确认。因此,这在您的代码中不是问题。防火墙阻止连接,或者托管服务的进程未侦听该端口。这可能是因为它根本没有运行或者因为它正在侦听不同的端口。
启动托管服务的进程后,请尝试使用
netstat -anb(需要管理员权限)来验证它是否正在运行并侦听预期的端口。更新:在 Linux 上,您可能需要执行
netstat -anp。