2

I have two simple projects in a single Visual Studio solution to understand how a ajax request works. One is a web service and the second one is a project consuming the web service. Here are the relevant code snippets.

Web Service #1st Project

Custom Classes.

public class JSONResponse
{
    public string message{ get; set; }
    public JSONResponse()
    {
        message = string.Empty;
    }
}
public class returnData
{
    public string UserValue { get; set; }
    public returnData()
    {
        UserValue = string.Empty;
    }
}

Web Method

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public JSONResponse returnData(returnData objEnter)
    {            
        JSONResponse jsObj = new JSONResponse();
        jsObj.message =  objEnter.UserValue;
        return jsObj;
    }
}

Consuming Application #2nd Project

Javascript Object Creation

    $(document).ready(function () {
        $("#btnSubmit").click(function () {
            debugger;
            var objEnter = {
                UserValue: $("#txtMsg").val()
            }
            pushToServer(objEnter, "returnData", "objEnter");
            // pushToServer(object,function to call,name of the object);
        });
    });

AJAX Request

        function pushToServer(dataToPass, functionToCall, jsonObjectName) {
            debugger;
            $.ajax({
                url: "http://localhost:12016/DisplayError.asmx/" + functionToCall,
                type: "POST",
                dataType: "json",
                data: "{" + jsonObjectName + ":" + JSON.stringify(dataToPass) + "}",
                timeout: 30000,
                //async: false,        
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    return data;
                    alert(data);
                },
                error: function (result) {
                    //alert(e);
                    alert(result.status + ' ' + result.statusText);
                }
            });
        }

But on inspecting through fiddler, I get the following HTTP 500 Error.

[InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/returnData'.]
   System.Web.Services.Protocols.WebServiceHandlerFactory.CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) +546417
   System.Web.Services.Protocols.WebServiceHandlerFactory.GetHandler(HttpContext context, String verb, String url, String filePath) +212
   System.Web.Script.Services.ScriptHandlerFactory.GetHandler(HttpContext context, String requestType, String url, String pathTranslated) +47
   System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +203
   System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +128
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

Chrome Console puts out the following error,

XMLHttpRequest cannot load http://localhost:12016/DisplayError.asmx/returnData. Origin http://localhost:12196 is not allowed by Access-Control-Allow-Origin.

The web service is running on port 12016, and the project is on port 12196.

I'm unable to understand what's causing the error.

Abijeet Patro
  • 2,842
  • 4
  • 37
  • 64

1 Answers1

2

In .NET Framework 1+, HTTP GET and HTTP POST are both disabled by default for security reasons. Make sure you change your application web.config to enable Get/Post for webservice calls:

<configuration>
    <system.web>
    <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
    </system.web>
</configuration>

There's also a possibility that your ajax call fails due to the same origin policy. Having your applications on two different ports, the browser assumes they are different domains and prevents ajax calls the service! You can either host both applications on the same domain or enable the CORS in your web-service application:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin","*");
}
Kamyar Nazeri
  • 25,786
  • 15
  • 50
  • 87
  • The web.config file should be modified in both the projects or only the web service project? – Mr_Green Dec 31 '12 at 10:17
  • The web-service accepts Get/Post calls, then it's the web-service project – Kamyar Nazeri Dec 31 '12 at 10:19
  • Still this doesnt work(I mean same error exists).. It seems to be same origin policy as you mentioned.. – Mr_Green Dec 31 '12 at 10:36
  • If you get HTTP 500 Error on the server, then it's something wrong with the web-service, however error in the browser stating *not allowed by Access-Control-Allow-Origin* must be resolved by enabling CORS as I mentioned above – Kamyar Nazeri Dec 31 '12 at 11:01