Reputation: 53
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
Please help me resolve problem! Thank you
Upvotes: 3
Views: 1933
Reputation: 459
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
Upvotes: 2
Reputation: 53
if (user != null)
{
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();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(cmd);
con.Close();
sqlDataAdapter.Fill(datatable);
int i = 0;
if (datatable.Rows.Count > 0)
{
foreach (DataRow dr in datatable.Rows)
{
json += "A" + i + ":{ID:'" + dr["ID"] + "',User:'" + dr["UserName"] + "'},";
i++;
}
json = json.Remove(json.Length - 1);
json += "}";
JObject json2 = JObject.Parse(json);
context.Response.Write(json2);
return;
}
else
json = "{'result':'false'}";
}
else
json = "{'result':'false'}";
JObject json3 = JObject.Parse(json);
context.Response.Write(json3);
return;
}
Upvotes: 1