I've probably made a really silly mistake, I am able to make a successful POST request to server. I am also able to get a response from server 201 as well as being able to view the json("requestid"). I am able to deserialize the JSON and parse requestid as a string (public string requestID). I have a timer (timer1) set up to poll the server every 1 second, the polling should start successfully if 201 created and does. However the problem I am having is that it does not include the requestid. Would someone be able to advise and tell me where I had gone wrong please?
namespace RestAPI
{
public enum httpVerb
{
GET,
POST,
PUT,
DELETE
}
class RESTAPI
{
public string endPoint { get; set; }
public httpVerb httpMethod { get; set; }
public string userPassword { get; set; }
public int sendAmount { get; set; }
public string location { get; set; }
public string requestId { get; set; }
public RESTAPI()
{
endPoint = string.Empty;
httpMethod = httpVerb.GET;
userPassword = string.Empty;
//requestId = string.Empty;
}
public string makeRequest()
{
string strResponseValue = string.Empty;
string result = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = httpMethod.ToString();
request.ContentType = "application/json";
request.Accept = "application/connect.v1+json";
String username = "mokhan";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + userPassword));
request.Headers.Add("Authorization", "Basic " + encoded);
if(httpMethod == httpVerb.POST)
{
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"transactionType\":\"SALE\"," + "\"amount\":" + sendAmount + "," +
"\"currency\":\"GBP\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
HttpWebResponse responseback = (HttpWebResponse)request.GetResponse();
//string result;
using (StreamReader rdr = new StreamReader(responseback.GetResponseStream()))
{
result = rdr.ReadToEnd();
}
if (responseback.StatusCode == HttpStatusCode.Created)
{
dynamic jsonObj = JsonConvert.DeserializeObject(result);
requestId = jsonObj.requestId.ToString();
return requestId;
}
return result;
}
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strResponseValue = reader.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
}
finally
{
if (response != null)
{
((IDisposable)response).Dispose();
}
}
return strResponseValue;
}
}
}
This code below shows my POST and GET requests to server, I have added the timer method to start in my POST request after I get a response and have added the code for polling in my timer method. I have also set string transactionid = rclient.requestId; and the called on rclient.endPoint = "https://" + txtBox.Text + "/pac" + "/terminals/" + txtBox3.Text + "/transactions/" + transactionid; to poll the server every 1 second but for some reason it's not picking up transactionid.
namespace RestAPI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void go_Click(object sender, EventArgs e)
{
RESTAPI rclient = new RESTAPI();
rclient.endPoint = "https://" + txtBox.Text + "/pac" + "/terminals/" + txtBox3.Text;
rclient.userPassword = txtbox2.Text;
debugOutput("REQUEST SENT");
string strResponse = string.Empty;
strResponse = rclient.makeRequest();
debugOutput(strResponse);
}
private void debugOutput(string strDebugText)
{
try
{
System.Diagnostics.Debug.Write(strDebugText + Environment.NewLine);
txtBoxResponse.Text = txtBoxResponse.Text + strDebugText + Environment.NewLine;
txtBoxResponse.SelectionStart = txtBoxResponse.TextLength;
txtBoxResponse.ScrollToCaret();
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message, ToString() + Environment.NewLine);
}
}
private void txtBox_TextChanged(object sender, EventArgs e)
{
}
private void Test_Click(object sender, EventArgs e)
{
RESTAPI rclient = new RESTAPI();
rclient.httpMethod = httpVerb.POST;
rclient.sendAmount = Convert.ToInt32(amount.Text);
rclient.endPoint = "https://" + txtBox.Text + "/pac" + "/terminals/" + txtBox3.Text + "/transactions";
rclient.userPassword = txtbox2.Text;
debugOutput("REQUEST SENT");
string strResponse = string.Empty;
strResponse = rclient.makeRequest();
debugOutput(strResponse);
timer1.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
RESTAPI rclient = new RESTAPI();
rclient.httpMethod = httpVerb.GET;
string transactionid = rclient.requestId;
rclient.endPoint = "https://" + txtBox.Text + "/pac" + "/terminals/" + txtBox3.Text + "/transactions/" + transactionid;
debugOutput("REQUEST SENT");
string strResponse = string.Empty;
strResponse = rclient.makeRequest();
debugOutput(strResponse);
}
}
}
Just solved the issue, in my public class RESTAPI, i un-commented this
//requestId = string.Empty;
once done, i was able to pick up the request ID as a string and then call it in my timer
string transactionid = rclient.requestId;
Related
I have created a web API controller and am trying to post data to my database. When I test the API in POSTMAN, I get a 200 OK Result but a false return for body.
I have tried changing from [FormBody] instead but that doesn't work either.
I have added the method as a Boolean to check but I just receive false.
Here's an actual link to a published api:
Add API and All data
Here's what I've tried in POSTMAN using Body -> raw -> JSON/Application
{
CityName: "Test1",
State: "PA",
Population: "0",
MHouseholdIncome: "0",
POwnerRenter: "0",
MHomeValue: "0",
MAge: "0",
UnemploymentRate: "0",
CrimeIndex: "0"
}
Here's my controller:
// POST: api/Cities/AddCity
[HttpPost()]
[HttpPost("AddCity")]
public Boolean AddCity([FromBody]City city)
{
if (city != null)
{
DBConnect objDB = new DBConnect();
SqlCommand objCmd = new SqlCommand();
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.CommandText = "AddCity";
objCmd.Parameters.AddWithValue("#theCity", city.CityName);
objCmd.Parameters.AddWithValue("#theState", city.State);
objCmd.Parameters.AddWithValue("#thePopulation", city.Population);
objCmd.Parameters.AddWithValue("#theIncome", city.MHouseholdIncome);
objCmd.Parameters.AddWithValue("#theOwner", city.POwnerRenter);
objCmd.Parameters.AddWithValue("#theHomeValue", city.MHomeValue);
objCmd.Parameters.AddWithValue("#theMedianAge", city.MAge);
objCmd.Parameters.AddWithValue("#theUnemploymentRate", city.UnemploymentRate);
objCmd.Parameters.AddWithValue("#theCrime", city.CrimeIndex);
int value = objDB.DoUpdateUsingCmdObj(objCmd);
if (value > 0)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
Here's my code:
protected void btnAdd_Click(object sender, EventArgs e)
{
City city = new City();
city.CityName = txtCity.Text;
city.State = ddStates.SelectedValue;
city.Population = int.Parse(txtPopulation.Text);
city.MHouseholdIncome = float.Parse(txtHouseholdIncome.Text);
city.POwnerRenter = float.Parse(txtOwnerRenter.Text);
city.MHomeValue = float.Parse(txtHomeValue.Text);
city.MAge = float.Parse(txtAge.Text);
city.UnemploymentRate = float.Parse(txtUnemploymentRate.Text);
city.CrimeIndex = float.Parse(txtCrimeIndex.Text);
JavaScriptSerializer js = new JavaScriptSerializer();
String jsonCity = js.Serialize(city);
try
{
WebRequest request = WebRequest.Create(webApiUrl + "AddCity/");
request.Method = "POST";
request.ContentLength = jsonCity.Length;
request.ContentType = "application/json";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(jsonCity);
writer.Flush();
writer.Close();
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
String data = reader.ReadToEnd();
reader.Close();
response.Close();
if (data == "true")
{
string msg = "The city was successfully added to the database.";
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + msg + "');", true);
}
else
{
string msg = "A problem occured while adding the city to the database. The data was not recorded.";
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + msg + "');", true);
}
}
catch (Exception ex)
{
string msg = "Error:" + ex.Message;
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + msg + "');", true);
}
}
}
City.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CityLibrary
{
public class City
{
public int CityID { get; set; }
public string CityName { get; set; }
public string State { get; set; }
public int Population { get; set; }
public float MHouseholdIncome { get; set; }
public float POwnerRenter { get; set; }
public float MHomeValue { get; set; }
public float MAge { get; set; }
public float UnemploymentRate { get; set; }
public float CrimeIndex { get; set; }
public City()
{
}
public City(int id, string name, string state, int ppl, float income,
float owner, float home, float age, float rate, float crime)
{
this.CityID = id;
this.CityName = name;
this.State = state;
this.Population = ppl;
this.MHouseholdIncome = income;
this.POwnerRenter = owner;
this.MHomeValue = home;
this.MAge = age;
this.UnemploymentRate = rate;
this.CrimeIndex = crime;
}
}
}
I expect the data to be added to the actual database.
Check the objCmd for null, and if not, check the DoUpdateUsingCmdObj method
I can get accesstoken but I don't know how to get username and uuid from accesstoken, when I login it's gave me something like that
{"accessToken":"123","clientToken":"123","selectedProfile":{"id":"123","name":"playername"},"availableProfiles":[{"id":"123","name":"playername"}]}
Thanks!
private vstrong textoid Signin_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
try
{
bool isSignedIn = false;
if (isSignedIn == true)
{
var request = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/invalidate");
request.ContentType = "application/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
dynamic json = JsonConvert.SerializeObject(new
{
accessToken = Settings.Default.accessToken,
clientToken = Settings.Default.clientToken
});
}
Settings.Default.UUID = null;
Settings.Default.accessToken = null;
Settings.Default.clientToken = null;
}
else
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/authenticate");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
dynamic json = JsonConvert.SerializeObject(new
{
agent = new
{
name = "Minecraft",
version = 1
},
username = email.Text,
password = password.Password
});
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
ACCESS_TOKEN = result;
}
}
}
catch (WebException)
{
MessageBox.Show("Login failed. Invalid username or password.");
}
}
string ACCESS_TOKEN;
public string GetAccessToken()
{
return ACCESS_TOKEN;
}
That is a JSON response, which you will need to deserialize to use most effectively. You can do this with the following code:
var loginResponse = JsonConvert.DeserializeObject<LoginResponse>(result);
Now, the MinecraftLoginResponse will need to be a class you create yourself, unless there is a library that you are using for this. JSON consists of variable value combinations, the values after the ':', separated by commas. {} denote an object, and [] a collection.
In the minecraft response, you have two objects; the response itself, and then the Profile object. C# code of this response is:
public class Profile
{
public string id { get; set; }
public string name { get; set; }
}
public class LoginResponse
{
public string accessToken { get; set; }
public string clientToken { get; set; }
public Profile selectedProfile { get; set; }
public List<Profile> availableProfiles { get; set; }
}
I made the above by running the example response through this website, then removing the SelectedProfile and AvailableProfile as these are, logically, going to be the same thing. (Selected will be one of the available profiles).
I am using this code to login with google. And trying to get user details.
else if (Session["loginTo"].ToString() == "google")
{
var url = Request.Url.Query;
if (url != "")
{
string queryString = url.ToString();
char[] delimiterChars = { '=' };
string[] words = queryString.Split(delimiterChars);
string codeg = words[1];
if (codeg != null)
{
//get the access token
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.Method = "POST";
Parameters = "code=" + codeg + "&client_id=" + ggl_app_key + "&client_secret=" + ggl_app_secret + "&redirect_uri=" + ggl_redirect_url + "&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream postStream = webRequest.GetRequestStream();
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
WebResponse response = webRequest.GetResponse();
postStream = response.GetResponseStream();
StreamReader reader = new StreamReader(postStream);
string responseFromServer = reader.ReadToEnd();
GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
if (serStatus != null)
{
string accessToken = string.Empty;
accessToken = serStatus.access_token;
//getgoogleplususerdataSer(accessToken);
if (!string.IsNullOrEmpty(accessToken))
{
// This is where you want to add the code if login is successful.
getgoogleplususerdataSer(accessToken);
}
}
}
}
}
}
}
}
public class GooglePlusAccessToken
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
public string id_token { get; set; }
public string refresh_token { get; set; }
}
private async void getgoogleplususerdataSer(string access_token)
{
try
{
HttpClient client = new HttpClient();
var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token;
client.CancelPendingRequests();
HttpResponseMessage output = await client.GetAsync(urlProfile);
if (output.IsSuccessStatusCode)
{
string outputData = await output.Content.ReadAsStringAsync();
GoogleUserOutputData serStatus = JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);
if (serStatus != null)
{
// You will get the user information here.
}
}
}
catch (Exception ex)
{
//catching the exception
}
}
public class GoogleUserOutputData
{
public string id { get; set; }
public string name { get; set; }
public string given_name { get; set; }
public string email { get; set; }
public string picture { get; set; }
}
}
}
I have written this code on my master page. But getting error at method call 'getgoogleplususerdataSer(accessToken);' error is "An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%# Page Async="true" %>"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Net.Http;
public partial class _Default : System.Web.UI.Page
{
protected string googleplus_client_id = "clientid";
protected string googleplus_client_sceret = "id";
protected string googleplus_redirect_url="http://localhost"; // Replace this with your Redirect URL; Your Redirect URL from your developer.google application should match this URL.
protected string Parameters;
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Contents.Count > 0)
{
if (Session["loginWith"] != null)
{
if (Session["loginWith"].ToString() == "google")
{
try
{
var url = Request.Url.Query;
if (url != "")
{
string queryString = url.ToString();
char[] delimiterChars = { '=' };
string[] words = queryString.Split(delimiterChars);
string code = words[1];
if (code != null)
{
//get the access token
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.Method = "POST";
Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code";
byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream postStream = webRequest.GetRequestStream();
// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
WebResponse response = webRequest.GetResponse();
postStream = response.GetResponseStream();
StreamReader reader = new StreamReader(postStream);
string responseFromServer = reader.ReadToEnd();
GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);
if (serStatus != null)
{
string accessToken = string.Empty;
accessToken = serStatus.access_token;
if (!string.IsNullOrEmpty(accessToken))
{
// getgoogleplususerdataSer(accessToken);
}
else
{ }
}
else
{ }
}
else
{ }
}
}
catch (Exception ex)
{
//throw new Exception(ex.Message, ex);
Response.Redirect("index.aspx");
}
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + googleplus_redirect_url + "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=" + googleplus_client_id;
Session["loginWith"] = "google";
Response.Redirect(Googleurl);
}
public class GooglePlusAccessToken
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
public string id_token { get; set; }
public string refresh_token { get; set; }
}
private async void getgoogleplususerdataSer(string access_token)
{
try
{
HttpClient client = new HttpClient();
var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token;
client.CancelPendingRequests();
HttpResponseMessage output = await client.GetAsync(urlProfile);
if (output.IsSuccessStatusCode)
{
string outputData = await output.Content.ReadAsStringAsync();
GoogleUserOutputData serStatus = JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);
if (serStatus != null)
{
// You will get the user information here.
}
}
}
catch (Exception ex)
{
//catching the exception
}
}
}
public class GoogleUserOutputData
{
public string id { get; set; }
public string name { get; set; }
public string given_name { get; set; }
public string email { get; set; }
public string picture { get; set; }
}
I don't know from where i can store the user information in my table,
actually I don't know about google authentication and i find ths=is code on stackoverflow
I just want to store all the information in a table and if a user is logged in for the first time the page should be redirected to new user page and if the user is old user the page should redirect to welcome page
To start with, I definitely agree that Google's documentation is a murky business.
There are a couple of different ways in which you can validate the integrity of the ID token on the server side (btw this is the page you're looking for):
"Manually" - constantly download Google's public keys, verify signature and then each and every field, including the iss one; the main advantage (albeit a small one in my opinion) I see here is that you can minimize the number of requests sent to Google).
"Automatically" - do a GET on Google's endpoint to verify this token
https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}
Using a Google API Client Library - like the official one.
Here's how this could look:
private const string GoogleApiTokenInfoUrl = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}";
public ProviderUserDetails GetUserDetails(string providerToken)
{
var httpClient = new MonitoredHttpClient();
var requestUri = new Uri(string.Format(GoogleApiTokenInfoUrl, providerToken));
HttpResponseMessage httpResponseMessage;
try
{
httpResponseMessage = httpClient.GetAsync(requestUri).Result;
}
catch (Exception ex)
{
return null;
}
if (httpResponseMessage.StatusCode != HttpStatusCode.OK)
{
return null;
}
var response = httpResponseMessage.Content.ReadAsStringAsync().Result;
var googleApiTokenInfo = JsonConvert.DeserializeObject<GoogleApiTokenInfo>(response);
if (!SupportedClientsIds.Contains(googleApiTokenInfo.aud))
{
Log.WarnFormat("Google API Token Info aud field ({0}) not containing the required client id", googleApiTokenInfo.aud);
return null;
}
return new ProviderUserDetails
{
Email = googleApiTokenInfo.email,
FirstName = googleApiTokenInfo.given_name,
LastName = googleApiTokenInfo.family_name,
Locale = googleApiTokenInfo.locale,
Name = googleApiTokenInfo.name,
ProviderUserId = googleApiTokenInfo.sub
};
}
What is the best way to convert a JSON object into querystrings to append to a GET Url? The POST is straight forward and gets read by my Web API backend.
{Name: 'Mike' } = ?Name=Mike
private static string MakeRequest(HttpWebRequest req, string data)
{
try
{
if (req.Method == Verbs.POST.ToString() || req.Method == Verbs.PUT.ToString() || req.Method == Verbs.DELETE.ToString())
{
var encodedData = Encoding.UTF8.GetBytes(data);
req.ContentLength = encodedData.Length;
req.ContentType = "application/json";
req.GetRequestStream().Write(encodedData, 0, encodedData.Length);
}
using (var response = req.GetResponse() as HttpWebResponse)
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
catch (WebException we)
{
if(we.Response == null)
{
return JsonConvert.SerializeObject(new { Errors = new List<ApiError> { new ApiError(11, "API is currently unavailable") }});
}
using (var response = we.Response as HttpWebResponse)
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
If the json object is flat as in your example, then
string json = #"{
""name"": ""charlie"",
""num"": 123
}";
var jObj = (JObject)JsonConvert.DeserializeObject(json);
var query = String.Join("&",
jObj.Children().Cast<JProperty>()
.Select(jp=>jp.Name + "=" + HttpUtility.UrlEncode(jp.Value.ToString())));
query would be name=charlie&num=123
I make this code to run in .Net Core:
public static string JsonToQuery(this string jsonQuery)
{
string str = "?";
str += jsonQuery.Replace(":", "=").Replace("{","").
Replace("}", "").Replace(",","&").
Replace("\"", "");
return str;
}
Example:
var _baseURI = "http://www.example.com/";
var endPoint = "myendpoint";
ExampleObjectModel requestModel = new ExampleObjectModel();
var requestModelJson = JsonConvert.SerializeObject(requestModel);
var url = string.Format("{0}{1}{2}", _baseURI, endPoint, requestModelJson.JsonToQuery());
Try this, work all object, in deep
public static class ExtensionMethods
{
public static string GetQueryString(this object obj, string prefix = "")
{
var query = "";
try
{
var vQueryString = (JsonConvert.SerializeObject(obj));
var jObj = (JObject)JsonConvert.DeserializeObject(vQueryString);
query = String.Join("&",
jObj.Children().Cast<JProperty>()
.Select(jp =>
{
if (jp.Value.Type == JTokenType.Array)
{
var count = 0;
var arrValue = String.Join("&", jp.Value.ToList().Select<JToken, string>(p =>
{
var tmp = JsonConvert.DeserializeObject(p.ToString()).GetQueryString(jp.Name + HttpUtility.UrlEncode("[") + count++ + HttpUtility.UrlEncode("]"));
return tmp;
}));
return arrValue;
}
else
return (prefix.Length > 0 ? prefix + HttpUtility.UrlEncode("[") + jp.Name + HttpUtility.UrlEncode("]") : jp.Name) + "=" + HttpUtility.UrlEncode(jp.Value.ToString());
}
)) ?? "";
}
catch (Exception ex)
{
}
return query;
}
}
To use: SomeObject.GetQueryString();
if your object(Entity) have a Children like this Entity :
public class Parent
{
public Child childs { get; set; } = new Child();
public int PageIndex { get; set; }
public int? PageSize { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
}
Your Can Use This Code For Build Query:
First Convert You Enrity Model To JObject
And Call This Method :
public static string GetQueryString(this JObject jObj)
{
return String.Join("&",
jObj.Children().Cast<JProperty>()
.Select(jp =>
{
if (jp.Value.Type == JTokenType.Object)
{
var arrValue = String.Join("&",
jObj.Values().Children().Cast<JProperty>()
.Select(jp => jp.Path + "=" + HttpUtility.UrlEncode(jp.Value.ToString())));
return arrValue;
}
else
{
var arrValue = String.Join("&", jp.Name + "=" + HttpUtility.UrlEncode(jp.Value.ToString()));
return arrValue;
}
}
)) ?? "";
}
Your Can Get Like This QueryString :
childs.Id=1&childs.Name="Test"&PageIndex=1&PageSize=1