Search code examples
c#asp.netasp.net-ajaxgeneric-handler

How To Return Data type JSON in ashx


I'm looking for a way to export the data into a JSON style. Please show me the way

<%@ WebHandler Language="C#" Class="API" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System.Web.Script.Serialization;
public class User
{
    public string type { get; set; }
    public string user { get; set; }
    public string pass { get; set; }

}
public class API : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";
    string strJson = new StreamReader(context.Request.InputStream).ReadToEnd();
    User user = JsonConvert.DeserializeObject<User>(strJson);
    string str = System.Configuration.ConfigurationManager.ConnectionStrings["conStr"].ConnectionString, json = "";
    if (user.type != null && user.user != null && user.pass != null)
    {
        SqlConnection con = new SqlConnection(str);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "SELECT ID,UserName From Partner Where UserName=@UserName And PassWord=@Pass";
        cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 100).Value = user.user;
        cmd.Parameters.Add("@Pass", SqlDbType.NVarChar, 100).Value = user.pass;
        if (ConnectionState.Closed == con.State)
            con.Open();
        DataTable datatable = new DataTable();
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);
        con.Close();
        sqlDataAdapter.Fill(datatable);
        if (datatable.Rows.Count > 0)
        {
            foreach (DataRow dr in datatable.Rows)
                //My data return;
        }
    }
}

Finally I want return data json
My Code HTML/Javascript

Please help me resolve problem! Thank you


Solution

  • I think you should use Web API. See more at https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/using-web-api-with-aspnet-web-forms