HTTP发布自我测试处理程序

时间:2012-01-19 14:01:12

标签: asp.net http httpwebrequest http-headers handler

我目前正在使用asp.net中的通用处理程序。我相信它目前处于一种等待POST的“倾听”状态。我期待一个带有文件名Header的POST,一旦收到处理程序将处理下载文件。我的处理程序代码如下:

Sub ProcessRequest(Byval context as HttpContext) Implements IHttpHanlder.ProcessRequest

If context.Request.HttpMethod() = "POST" Then
Dim Reader as New StreamReader(context.Request.InputStream)
Dim contents as String = reader.ReadtoEnd()

Dim filename as String = context.Request.Headers(("filename"))
System.IO.File.Writealltext(ConfigurationManager.AppSettings("outputdirectory"), contents)
Else
context.Response.ContentType = "text/plain"
context.Response.ContentType("Handler is alive")
End If

End Sub

我想复制一篇帖子,看看是否成功了。是否可以从我的机器上的另一个程序生成并发送此帖子。我尝试过一些教程,包括这个教程

SO - POST Tutorial

我觉得我使用此代码(来自上一个链接)已经得到了最接近的代码

Using wc as New System.Net.WebClient
wc.UploadFile("http://localhost:Port/local/of/handler", "C:\local\of\file.txt")
End Using

我从远程服务器收到500错误。这会是处理程序代码的问题吗?或者我只是没有做出正确的POST类型?

当搞乱wc.Headers()/ Darin的建议时,我仍然会收到500错误。例外情况如下。

System.Net.WebException: The remote server returned an error: (500) Internal Server Error
at System.Net.HttpWebRequest.GetResponse()
at System.Net.Webclient.GetWebResponse(WebRequest request)
at System.Net.WebClient.WebClientWriteStream.Dispose(Boolean disposing)
at System.IO.Stream.Close()
at System.IO.Stream.Dispose()
at TestPOSTGETEXE.Form1.Button4_Click(Object sender, EventArgs e) in C:\blah\blah\..\..\..\

1 个答案:

答案 0 :(得分:1)

试试这样:

Using wc As New System.Net.WebClient
    wc.Headers("filename") = "file.txt"
    Using writer = wc.OpenWrite("http://localhost:Port/local/of/handler")
        Dim file = System.IO.File.ReadAllBytes("C:\local\of\file.txt")
        writer.Write(file, 0, file.Length)
    End Using
End Using