Return JSON with ASP.NET/C#

1

I have the following codes

Default.aspx

<script type="text/javascript">
        /* Relógio */
        function startTime() {
            $.ajax({
                type: 'POST',
                url: 'Default.aspx/GetNetworkTime',
                data: "{}",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (dados) {
                    var m;
                    var s;
                    if (dados.minuto < 10) {
                        m = "0" + dados.minuto;
                    } else {
                        m = dados.minuto;
                    }
                    if (dados.segundo < 10) {
                        s = "0" + dados.segundo;
                    } else {
                        s = dados.segundo;
                    }
                    document.getElementById('txt').innerHTML = dados.hora + ":" + m + ":" + s;
                }
            });
            t = setTimeout('startTime()', 500);
        };
    </script>

Default.aspx.cs

using System.Web.Services;

namespace LPGPontoKH
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod]
        public static string GetNetworkTime()
        {
            DateTime datetime = DateTime.Now;

            var resultado = new
            {
                hora = datetime.Hour,
                minuto = datetime.Minute,
                segundo = datetime.Second
            };
            //O JavaScriptSerializer vai fazer o web service retornar JSON
            JavaScriptSerializer js = new JavaScriptSerializer();

            return js.Serialize(resultado);
        }

    }
}

My startTime javascript function is executed, however the GetNetworkTime method is not called. Does anyone know what's missing?

Generated log error.

  

{"Message": "Failed to   Authenticate. "," StackTrace ": null," ExceptionType ":" System.InvalidOperationException "}

    
asked by anonymous 26.01.2015 / 18:42

1 answer

3

To make this ajax call work in your WebForms application, you will need to change the route setting.

In the file "~ / App_Start / RouteConfig.cs", change from:

settings.AutoRedirectMode = RedirectMode.Permanent;

To:

settings.AutoRedirectMode = RedirectMode.Off;

After you make this change and run the application again, you will see that WebMethod GetNetworkTime () will run in the code behind the page.

    
10.02.2015 / 01:45