简体   繁体   中英

Json object return not working using webservice (.asmx) in asp.net

I'm using asp.net web service .asmx to transport json data. I have following code which seems not to be working.

    $.ajax({
            type: "POST",
            url: "../../App_Code/jsonWebService/getValue",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (output) {
                alert(output);
                $(config.captchaQuestion).html(output[0] + " + " + output[1] + " =");
                $(config.captchaHidden).val(output[2]);
            }
        });

And my code inside jsonWebService.cs of asmx file is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;

/// <summary>
/// Summary description for jsonWebService
// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment        the following line. 
 [System.Web.Script.Services.ScriptService]
public class jsonWebService : System.Web.Services.WebService {


[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Array getValue()
{
    Random getRandom = new Random();
    int rand1 = getRandom.Next(0, 9);
    int rand2 = getRandom.Next(0, 9);
    int sum = rand1 + rand2;
    int[] jsonObject = new int[3] { rand1, rand2, sum };
    return jsonObject;
}

}

And I'm getting Forbidden error 403. Thanks in advance.

You are not allowed to directly browse the files in app_code folder. You have to give the path of asmx file and use the webservice name.

Change

url: "../../App_Code/jsonWebService/getValue",

To

url: "../../jsonWebService.asmx/getValue",

The url cannot be:

"../../App_Code/jsonWebService/getValue",

because App_Code is a special folder which stores classes/model/any other code files and we can access the files from that folder directly without specifying the folder path(App_Code).. ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM