[asp.net] Request format is unrecognized for URL unexpectedly ending in

This is not a question - posting it here for reference:

When consuming a WebService, I got the following error:

Request format is unrecognized for URL unexpectedly ending in /myMethodName

This question is related to asp.net web-services

The answer is


I use following line of code to fix this problem. Write the following code in web.config file

<configuration>
    <system.web.extensions>
       <scripting>
       <webServices>
       <jsonSerialization maxJsonLength="50000000"/>
      </webServices>
     </scripting>
   </system.web.extensions>
</configuration>

Superb.

Case 2 - where the same issue can arrise) in my case the problem was due to the following line:

<webServices>
  <protocols>
    <remove name="Documentation"/>
  </protocols>
</webServices>

It works well in server as calls are made directly to the webservice function - however will fail if you run the service directly from .Net in the debug environment and want to test running the function manually.


I also got this error with apache mod-mono. It looks like the documentation page for webservice is not implemented yet in linux. But the webservice is working despite this error. You should see it by adding ?WSDL at the end of url, i.e http://localhost/WebService1.asmx?WSDL


In my case the error happened when i move from my local PC Windows 10 to a dedicated server with Windows 2012. The solution for was to add to the web.config the following lines

<webServices>
        <protocols>
               <add name="Documentation"/>
        </protocols>
</webServices>

For the record I was getting this error when I moved an old app from one server to another. I added the <add name="HttpGet"/> <add name="HttpPost"/> elements to the web.config, which changed the error to:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at BitMeter2.DataBuffer.incrementCurrent(Int64 val)
   at BitMeter2.DataBuffer.WindOn(Int64 count, Int64 amount)
   at BitMeter2.DataHistory.windOnBuffer(DataBuffer buffer, Int64 totalAmount, Int32 increments)
   at BitMeter2.DataHistory.NewData(Int64 downloadValue, Int64 uploadValue)
   at BitMeter2.frmMain.tickProcessing(Boolean fromTimerEvent)

In order to fix this error I had to add the ScriptHandlerFactory lines to web.config:

  <system.webServer>
    <handlers>
      <remove name="ScriptHandlerFactory" />
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </handlers>
  </system.webServer>

Why it worked without these lines on one web server and not the other I don't know.


Make sure you disable custom errors. This can mask the original problem in your code:

change

<customErrors defaultRedirect="~/Error" mode="On">

to

<customErrors defaultRedirect="~/Error" mode="Off">

In our case the problem was caused by the web service being called using the OPTIONS request method (instead of GET or POST).

We still don't know why the problem suddenly appeared. The web service had been running for 5 years perfectly well over both HTTP and HTTPS. We are the only ones that consume the web service and it is always using POST.

Recently we decided to make the site that host the web service SSL only. We added rewrite rules to the Web.config to convert anything HTTP into HTTPS, deployed, and immediately started getting, on top of the regular GET and POST requests, OPTIONS requests. The OPTIONS requests caused the error discussed on this post.

The rest of the application worked perfectly well. But we kept getting hundreds of error reports due to this problem.

There are several posts (e.g. this one) discussing how to handle the OPTIONS method. We went for handling the OPTIONS request directly in the Global.asax. This made the problem dissapear.

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var req = HttpContext.Current.Request;
        var resp = HttpContext.Current.Response;

        if (req.HttpMethod == "OPTIONS")
        {
            //These headers are handling the "pre-flight" OPTIONS call sent by the browser
            resp.AddHeader("Access-Control-Allow-Methods", "GET, POST");
            resp.AddHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, SOAPAction");
            resp.AddHeader("Access-Control-Max-Age", "1728000");
            resp.End();
        }
    }

Despite 90% of all the information I found (while trying to find a solution to this error) telling me to add the HttpGet and HttpPost to the configuration, that did not work for me... and didn't make sense to me anyway.

My application is running on lots of servers (30+) and I've never had to add this configuration for any of them. Either the version of the application running under .NET 2.0 or .NET 4.0.

The solution for me was to re-register ASP.NET against IIS.

I used the following command line to achieve this...

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

a WebMethod which requires a ContextKey,

[WebMethod]
public string[] GetValues(string prefixText, int count, string contextKey)

when this key is not set, got the exception.

Fixing it by assigning AutoCompleteExtender's key.

ac.ContextKey = "myKey";

I was getting this error until I added (as shown in the code below) $.holdReady(true) at the beginning of my web service call and $.holdReady(false) after it ends. This is jQuery thing to suspend the ready state of the page so any script within document.ready function would be waiting for this (among other possible but unknown to me things).

<span class="AjaxPlaceHolder"></span>
<script type="text/javascript">
$.holdReady(true);
function GetHTML(source, section){
    var divToBeWorkedOn = ".AjaxPlaceHolder";
    var webMethod = "../MyService.asmx/MyMethod";
    var parameters = "{'source':'" + source + "','section':'" + section + "'}";

    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        xhrFields: {
            withCredentials: false
        },
        crossDomain: true,
        success: function(data) {
            $.holdReady(false);
            var myData = data.d;
            if (myData != null) {
                $(divToBeWorkedOn).prepend(myData.html);
            }
        },
        error: function(e){
            $.holdReady(false);
            $(divToBeWorkedOn).html("Unavailable");
        }
    });
}
GetHTML("external", "Staff Directory");
</script>

In html you have to enclose the call in a a form with a GET with something like

<a href="/service/servicename.asmx/FunctionName/parameter=SomeValue">label</a>

You can also use a POST with the action being the location of the web service and input the parameter via an input tag.

There are also SOAP and proxy classes.


I did not have the issue when developing in localhost. However, once I published to a web server, the webservice was returning an empty (blank) result and I was seeing the error in my logs.

I fixed it by setting my ajax contentType to :

"application/json; charset=utf-8"

and using :

JSON.stringify()

on the object I was posting.

var postData = {data: myData};
$.ajax({
                type: "POST",
                url: "../MyService.asmx/MyMethod",
                data: JSON.stringify(postData), 
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    console.log(data);
                },
                dataType: "json"
            });

In my case i had an overload of function that was causing this Exception, once i changed the name of my second function it ran ok, guess web server doesnot support function overloading


Make sure you're using right method: Post/Get, right content type and right parameters (data).

$.ajax({
    type: "POST",
    url: "/ajax.asmx/GetNews",
    data: "{Lang:'tr'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) { generateNews(msg); }
})

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to web-services

How do I POST XML data to a webservice with Postman? How to send json data in POST request using C# org.springframework.web.client.HttpClientErrorException: 400 Bad Request How to call a REST web service API from JavaScript? The request was rejected because no multipart boundary was found in springboot Generating Request/Response XML from a WSDL How to send a POST request using volley with string body? How to send post request to the below post method using postman rest client How to pass a JSON array as a parameter in URL Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw