I get this error: The remote server returned an error: (401) Unauthorized. when posting to ASHX file with XML over HTTP

Posted on 2008-10-30
Last Modified: 2012-05-05
I get this error: The remote server returned an error: (401) Unauthorized. when posting to ASHX file with XML over HTTP.

The purpose of this code is to be able to post XML over HTTP (I have to do this because this is how a product I am using communicates) to an Generic Handler (ASHX file) in ASP.NET/VB.NET but I am getting this error: The remote server returned an error: (401) Unauthorized.

I have attached the code for review.  The site is set up properly in IIS and I can browse other ASP.NET pages just fine in the site and I can also just browse the ASHX page directly and it displays "Hello World" as expected.  But when I try to post to the ASHX page from the posting ASPX page, I get that error.


<%@ Page Language="VB" %>

<%@ Import Namespace="System.Net" %>

<%@ Import Namespace="System.IO" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">


<script runat="server">


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

        Response.Write(PostXml("http://vm01/sign/testxmloverhttp/listener.ashx", My.Computer.FileSystem.ReadAllText(Server.MapPath("XMLFile.xml"), Encoding.UTF8)))

    End Sub


    Public Function PostXml(ByVal url As String, ByVal xml As String) As String

        Dim returnValue As String = ""


            Dim bytes As Byte() = Encoding.UTF8.GetBytes(xml)

            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)

            request.Method = "POST"

            request.ContentLength = bytes.Length

            request.ContentType = "text/xml"

            Using requestStream As Stream = request.GetRequestStream()

                requestStream.Write(bytes, 0, bytes.Length)

            End Using


            Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)

            If response.StatusCode <> HttpStatusCode.OK Then

                Dim message As String = [String].Format("POST failed. Received HTTP {0}", response.StatusCode)

                Throw New ApplicationException(message)

            End If

            Dim rs As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)

            Dim receiveStream As Stream = rs.GetResponseStream()

            Dim encode As Encoding = System.Text.Encoding.GetEncoding("utf-8")

            Dim readStream As New StreamReader(receiveStream, encode)

            Dim read(256) As [Char]

            Dim count As Integer = readStream.Read(read, 0, 256)

            While count > 0

                Dim str As New [String](read, 0, count)

                returnValue += str

                count = readStream.Read(read, 0, 256)

            End While



        Catch ex As Exception

            Return ex.Message

        End Try

        Return returnValue

    End Function



<html xmlns="">

<head runat="server">




    <form id="form1" runat="server">










<%@ WebHandler Language="VB" Class="Listener" %>


Imports System

Imports System.Web


Public Class Listener : Implements IHttpHandler


    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        context.Response.ContentType = "text/HTML"

        context.Response.Write("Hello World")

    End Sub


    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable


            Return False

        End Get

    End Property


End Class

Open in new window

Question by:edenmachine
1 Comment

Accepted Solution

edenmachine earned 0 total points
ID: 22844209
Ah - I had to allow read perms to LocalMachineName\Users to the file/directory and that fixed it.

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now