问题
I am can try to run NHTTP(simple asynchronous HTTP server written in C# for the .NET framework. You can download this dll in nuget, or view source code on github) But i am cant write my own response to client from my server, because i am can't write to OutputStream.
My powershell script:
Add-Type -Path "NHttp.dll"
$server = New-Object NHttp.HttpServer
$server.EndPoint = new-object System.Net.IPEndPoint ([System.Net.IPAddress]::Parse("127.0.0.1"), 8080)
$RequestReceived = {
$request = $EventArgs.Request
$response = $EventArgs.Response
$global:response = $response.OutputStream.CanWrite
$writer = New-Object System.IO.StreamWriter($response.OutputStream)
$writer.AutoFlush = $true
$writer.WriteLine("Hello World")
}
Register-ObjectEvent -InputObject $server -EventName RequestReceived -SourceIdentifier RequestReceived -Action $RequestReceived
$server.Start()
Always when my server receive request from client $global:response=False
An error occurring in the Event, which occurs when the server receives a request:
writeErrorStream : True
PSMessageDetails :
Exception : System.Management.Automation.MethodInvocationException: Exce
ption when calling the ".ctor" with "1" argument: "Stream wa
s not writable" ---> System.ArgumentException: Stream was no
t writable.
at System.IO.StreamWriter..ctor(Stream stream, Encoding en
coding, Int32 bufferSize, Boolean leaveOpen)
at System.IO.StreamWriter..ctor(Stream stream)
--- End of inner exception stack trace ---
at System.Management.Automation.DotNetAdapter.AuxiliaryCon
structorInvoke(MethodInformation methodInformation, Object[]
arguments, Object[] originalArguments)
at Microsoft.PowerShell.Commands.NewObjectCommand.CallCons
tructor(Type type, ConstructorInfo[] constructors, Object[]
args)
TargetObject :
CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationExceptio
n
FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Comman
ds.NewObjectCommand
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at <ScriptBlock>, C:\powershell_scripts\tmp\nhttp.ps1: line 18
PipelineIterationInfo : {}
And server response clean white page and StatusCode 200 to client.
But example for C# work perfectly:
using (var server = new HttpServer())
{
server.RequestReceived += (s, e) =>
{
using (var writer = new StreamWriter(e.Response.OutputStream))
{
writer.Write("Hello world!");
}
};
server.Start();
Process.Start(String.Format("http://{0}/", server.EndPoint));
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
Such behavior within the Action block when called Event created by Register-ObjectEvent occurs to me is not the first time. I try to solve it, changing "apartment" model(STA and MTA), but it not solve the problem. If you need i am have more examples.
来源:https://stackoverflow.com/questions/33251038/cant-write-to-stream-inside-event