Click here to Skip to main content
14,451,081 members
Rate this:
Please Sign up or sign in to vote.
Hi,
I'm setting up a website to act as our API to our internal database.
I think I'm going in the right direction but keep hitting a brick wall.
Server code and my test routine below.
Error2 = ProtocolError
Any pointers to resolve would be greatly appreciated!
Paul

What I have tried:

NOTE:
Just Added:
<system.web>
  <webServices>
    <protocols>
      <add name="HttpGet"/>
      <add name="HttpPost"/>
    </protocols>
  </webServices>
</system.web>

to Webserver config.
Now:
https://WEBSITE/service.asmx/TestRest
Returns:
<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://localhost:51561/APIServer/">{"qtest":{"response":"hello"}}</string>

Getting better but my test site still fails. Same error as below.





Server Code: Service.vb file:

<WebService(Namespace:="http://localhost:51561/APIServer/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function TestRest() As String

        Dim sjon As String = "{"
        sjon = sjon & """qtest"":{""response"":""hello""}"
        sjon = sjon & "}"

        Return sjon
    End Function
End Class

Service.asmx file:
<%@ WebService Language="vb" CodeBehind="~/App_Code/Service.vb" Class="Service" %>


Calling the Webserver with this:

        Dim returnedData As String = ""
        Dim error2 As String = ""

        Try

            Dim DataToSend As String = ""
 

            Dim urlLive As String = "https://WEBSITENAME/Service.asmx/TestRest"  

            Dim postAddress = New Uri(urlLive)

            Dim request = DirectCast(WebRequest.Create(postAddress), HttpWebRequest)

            request.Method = "POST"
            request.ContentType = "application/json"  

            request.Headers.Add("AcceptTypes", "text/plain")
            request.Headers.Add("Accept-Language", "en-US")
            request.Headers.Add("UserAgent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)")

            request.ContentLength = Len(DataToSend).ToString
 

            request.ProtocolVersion = HttpVersion.Version11

            Dim postByteData As Byte() = System.Text.UTF8Encoding.UTF8.GetBytes(DataToSend)
            request.ContentLength = postByteData.Length

            Using postStream As Stream = request.GetRequestStream()
                postStream.Write(postByteData, 0, postByteData.Length)
            End Using

            Using resp = TryCast(request.GetResponse(), HttpWebResponse)
                Dim reader = New StreamReader(resp.GetResponseStream())
                returnedData = reader.ReadToEnd()
            End Using

        Catch exw As WebException

            Try
                Dim httpResponse As HttpWebResponse = CType(exw.Response, HttpWebResponse)
                returnedData = "Error - " & CInt(httpResponse.StatusCode).ToString() & " - " & httpResponse.StatusCode.ToString()

                error2 = exw.Status.ToString

            Catch ex As Exception
                returnedData = "Error - Site"
            End Try

        Catch ex As Exception

            returnedData = "Error - Exception Error"

        End Try

        error2 = error2 & ""
        returnedData = returnedData & ""
Posted
Updated 5-May-17 3:40am
v2
Comments
Wessel Beulink 5-May-17 6:25am
   
Can you post down the 500 error?
Also what happen if you directly call: https://WEBSITENAME/Service.asmx/TestRest from your browser?
Member 10103170 5-May-17 6:37am
   
"Error - 500 - InternalServerError"



https://WEBSITENAME/service.asmx/TestRest

Returns:
Request format is unrecognized for URL unexpectedly ending in '/TestRest'.
Stack Trace:
[InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/TestRest'.]
System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +484886
System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +209
System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +47
System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +346
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
F-ES Sitecore 5-May-17 7:27am
   
Have you googled the error message and at least tried some of the suggestions?
Rate this:
Please Sign up or sign in to vote.

Solution 1

You have an error on your namespace you are using a fixed url:
<WebService(Namespace:="http://localhost:51561/APIServer/")> _


if you used dynamic the url should be:
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _


You should use dynamic url binding or change the localhost:51561 to WEBSITENAME:{port}
But i would choose the dynamic way than you don't have to worry about this. You can set this in properties of your project.
I have a nice tutorials from codeproject here: [How-to-make-your-Web-Reference]

if you not calling a dynamic url you need to set the url in your application before you call it.

This should fix your 500 error.

The best way to use you webservice is just add the url to your project under reference, will make it a lot easier for you instead of using a WebRequest.

Just go to your project and say: add refenerce => service reference. Past down your url and you should be able to use it in your project with the result and comments etc.
Here a example how to use your soup service when added:

Dim service As New ServiceReference1.Service1SoapClient
Dim test = service.TestRest()
   
Comments
Member 10103170 5-May-17 8:00am
   
https://WebsiteName/service.asmx/TestRest

Now gives me:
<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="https://WebsiteName/">{"qtest":{"response":"hello"}}

But my test website still fails on error 500. Does that mean now its my test website rather than my server code? Thanks
Wessel Beulink 5-May-17 8:12am
   
You deployed your site with http://localhost:51561/APIServer/ so:
https://WebsiteName/APIServer/qtest is not available in your case.

Because the api will look for:
http://localhost:51561/APIServer/qtest

If you change your Namespace to https://WebsiteName/APIServer and deploy it again it will probably work.


You can try but i'll definitely recommend you to use soap server reference. Or a restSharp api or something. Makes the coding much smoother :)
Member 10103170 5-May-17 8:41am
   
Thanks Wessel - your comments made me look in the right direction.
Paul :-)
Rate this:
Please Sign up or sign in to vote.

Solution 2

The server code was missing the first line (stopped it from being accessed via a script..):

<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="https://WEBSITENAME/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
    Inherits System.Web.Services.WebService
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100