尝试通过ajax访问Web服务时出现HTTP 500错误

时间:2012-12-30 19:47:45

标签: asp.net ajax jquery

我在一个Visual Studio解决方案中有两个简单的项目来理解ajax请求的工作原理。一个是Web服务,第二个是使用Web服务的项目。以下是相关的代码段。

网络服务#第一个项目

自定义类。

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;
    }
}

网络方法

[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;
    }
}

使用应用程序#第二个项目

Javascript对象创建

    $(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请求

        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);
                }
            });
        }

但是在通过提琴手检查时,我得到以下 HTTP 500错误

[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控制台会发出以下错误,

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

Web服务在端口12016上运行,项目在端口12196上。

我无法理解导致错误的原因。

1 个答案:

答案 0 :(得分:2)

出于安全原因,

In .NET Framework 1+, HTTP GET and HTTP POST are both disabled by default。确保更改应用程序web.config以启用Web服务调用的Get / Post:

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

由于same origin policy,您的ajax调用可能会失败。将您的应用程序放在两个不同的端口上,浏览器假定它们是不同的域并阻止ajax调用该服务!您可以在同一个域中托管两个应用程序,也可以在Web服务应用程序中启用CORS

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin","*");
}