Not able to get query string - asp.net

I am using the below code for setting URL in the current http context
public HttpContext SetNewHttpContext(string uRL)
{
var httpRequest = new HttpRequest("", uRL, "");
var httpResponse = new HttpResponse(new StringWriter());
return new HttpContext(httpRequest, httpResponse);
}
Invoking it as under
HttpContext.Current = SetNewHttpContext("http://root/test.aspx?userid=319279549&name=xyz");
var val = HttpContext.Current.Request.QueryString["userid"];
But i am not able to get the value of the querystring(userid here) and getting null.
Why?
Please help

Uri tempUri = new Uri("http://root/test.aspx?userid=319279549&name=xyz");
string sQuery = tempUri.Query;
NameValueCollection queryString =
System.Web.HttpUtility.ParseQueryString(sQuery ,Encoding.UTF8);

Related

Object becomes null after calling HTTPClient.PostAsJsonAsync to access Web Api

In my web form (ASP .Net 4.8, VB .Net), I have calling the following function from code-behind submit sales transaction via web api:
Public Async Function SendSale(fs As SaleTxnReqModel) As Task(Of SaleTxnRespModel)
Dim returnData As SaleTxnRespModel = New SaleTxnRespModel()
Dim apiUrl = "Sales/SendSale"
Dim resultRemark As String = String.Empty
Try
Using client = New HttpClient()
client.BaseAddress = New Uri(AppComp.NormalizeBaseUrl(constWebApiUri))
client.DefaultRequestHeaders.Accept.Clear()
client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
Dim jsonString As String = JsonConvert.SerializeObject(fs)
Dim content = New StringContent(jsonString, Encoding.UTF8, "application/json")
Dim response As HttpResponseMessage = Await client.PostAsJsonAsync(apiUrl, content)
returnData = Await response.Content.ReadAsAsync(Of SaleTxnRespModel)()
If Not response.IsSuccessStatusCode Then
resultRemark = AppComp.SetWebServStatusText(response.StatusCode)
End If
End Using
Catch ex As Exception
resultRemark = AppComp.GetExceptionMessage(ex)
Finally
returnData.REMARK = resultRemark
End Try
Return returnData
End Function
At the receiving web api, the request object has become null. 
[Route("SendFuelSale")]
[HttpPost]
public IActionResult SendFuelSale(SaleTxnReqModel txn)
{
// Process sales transaction...
}
I have tried using SendAsync method and it worked:
Dim jsonString As String = JsonConvert.SerializeObject(fs)
Dim content = New StringContent(jsonString, Encoding.UTF8, "application/json")
Dim request = New HttpRequestMessage(HttpMethod.Post, apiUrl)
request.Content = content
Dim response As HttpResponseMessage = Await client.SendAsync(request).ConfigureAwait(False)
I just wonder what went wrong when using PostAsJsonAsync  method.
Any idea? Please adivse. Thanks.

Post on FB fan page from ASP.NET

I want to post FB post on my fan page using ASP.NET. I am able to post on my fan page, but as an admin I can see all the posts. But people who have liked the page are not able to see the posts.
If I manually post anything on the page that particular post will be seen to others.
Please help.
I am using the following code
string app_id = "214545998669814";
string app_secret = "8cd4e507b943bb34bfb0c33830cbe2a9";
string scope = "publish_stream,manage_pages,offline_access,publish_actions";
if (Request["code"] == null)
{
Response.Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = System.Net.WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
//meh.aspx?token1=steve&token2=jake&...
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
dynamic parameters = new ExpandoObject();
parameters.message = "this is from fan page4.";
parameters.link = string.Empty;
parameters.picture = string.Empty;
parameters.name = "Article Title";
parameters.caption = "Caption for the link";
//446533181408238 is my fan page
client.Post("/548306908572853/feed", parameters);

Web API Login with Cookie

I have an ASP.Net Web API and the documentation states I need to save an Auth Token to a cookie then pass it back for API requests. I can get the Auth Token without a problem. My question is what is the best way to save the cookie and send it back in the request.
I create a cookie in the RequestMessage, but I cannot find a way to send it back when making a request against the API. How do I preserve the state of the Login/cookie.
Any help is greatly appreciated, thanks.
Update
I am now able to obtain the cookie from the response. I am using this tutorial. http://www.asp.net/web-api/overview/working-with-http/http-cookies Let me point out if you want to use this tutorial make sure you update the Web API 4's code base. In the below method i am trying to simply, Login and Logout. However, I am receiving an Error Code 500.
public HttpWebResponse InitializeWebRequest()
{
//HttpResponseMessage logoutMessage = await Logout("bla");
string responseData = string.Empty;
string url = GetServerEndPoint();
string authToken = string.Empty;
string loginInstance = "https://example.com";
// Create request.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Method = "POST";
request.ContentType = "application/json";
request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
if (response.StatusCode == HttpStatusCode.OK)
{
using (System.IO.StreamReader responseReader = new System.IO.StreamReader(request.GetResponse().GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
IList<string> authHeader = responseData.Split('{', '}').ToList();
authToken = authHeader[2].Substring(13, 25);
string sessionId = response.Headers.Get(8);
var nv = new NameValueCollection();
nv["sid"] = sessionId;
nv["token"] = authToken;
CookieHeaderValue cookieVal = new CookieHeaderValue("session", nv);
// Log out
string loginInstance2 = "https://example.com";
HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create(loginInstance2);
request2.Method = "POST";
request2.ContentType = "application/json";
request2.Headers.Add(nv);
HttpWebResponse response2 = (HttpWebResponse)request2.GetResponseAsync().Result;
}
return response;
}
WOW WHAT A PAIN!
I have no idea why this took me so long to figure out, but after hours and hours and DAYs, of trying to get this stupid auth to work I finally figured it out. Here is the code.
One weird thing is I had to create the header format for the cookie. Which by definition isn't a true cookie, it is a damn header value. I had to create the header title, because when I extracted the JSON object from the file and converted it to string I was unable to keep the format in tact from the file.
public HttpWebResponse InitiliazeWebRequest()
{
string responseData = string.Empty;
string loginInstance = "url + logincreds";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Method = "POST";
request.ContentType = "application/json";
request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
if (response.StatusCode == HttpStatusCode.OK)
{
using (System.IO.StreamReader responseReader = new System.IO.StreamReader(request.GetResponse().GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
var toke = response.Headers.Get("authToken");
JObject o = JObject.Parse(responseData);
_authToken = (string)o["response"]["authToken"].ToString();
return response;
}
return response;
}
public HttpWebResponse LogOut()
{
string responseData = string.Empty;
string loginInstance = "https://www.example.com/logout";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("Cookie: authToken=" + _authToken);
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
if (response.StatusCode == HttpStatusCode.OK)
{
using (System.IO.StreamReader responseReader = new System.IO.StreamReader(request.GetResponse().GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
return response;
}
return response;
}

how to parse xml string from Post method response?

I have a xml string that return from Post method:
private static void GetResponseCallback(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
HttpStatusCode rcode = response.StatusCode;
var stream = new GZipInputStream(response.GetResponseStream());
using (StreamReader reader = new StreamReader(stream))
{
responseString = reader.ReadToEnd();
}
response.Close();
}
The responseString is the string I want to parse, using parseXmlString class below. However I can't call the method parseXmlString directly because of the static. How can I pass the responseString to the parseXmlString method to have them parse out and bind to the listBox. Or anyway to have the same result would be great.
void parseXmlString()
{
byte[] byteArray = Encoding.UTF8.GetBytes(responseString);
MemoryStream str = new MemoryStream(byteArray);
str.Position = 0;
XDocument xdoc = XDocument.Load(str);
var data = from query in xdoc.Descendants("tracks").Elements("item")
select new searchResult
{
artist = (string)query.Element("artist"),
album = (string)query.Element("album"),
track = (string)query.Element("track"),
// artistA = (string)query.Element("artists").Element("artist"),
};
// ListBox lb = new ListBox();
listBox1.ItemsSource = data;
var data1 = from query in xdoc.Descendants("artists").Elements("item")
select new searchResult
{
artistA = (string)query.Element("artist"),
};
listBox2.ItemsSource = data1;
}
Your approach is inversed logic. You know that you can have return values on methods, right?-)
What you need to do is let your ParseXmlString method take the responseString as a parameter, and let it return the created IEnumerable, like this:
private IEnumerable<SearchResult> ParseXmlString(responseString)
{
XDocument xdoc = XDocument.Load(responseString);
var data =
from query in xdoc.Descendants("tracks").Elements("item")
select new SearchResult
{
Artist = (string)query.Element("artist"),
Album = (string)query.Element("album"),
Track = (string)query.Element("track"),
};
return
from query in xdoc.Descendants("artists").Elements("item")
select new SearchResult
{
ArtistA = (string)query.Element("artist"),
};
}
And change your async code handling, to perform a callback to your UI thread, when it's done reading out the responseString.
Then, on your UI thread, you would do:
// This being your method to get the async response
GetResponseAsync(..., responseString =>
{
var searchResults = ParseXmlString(responseString);
listBox2.ItemsSource = searchResults;
})
You can see this answer, if you need some basic understanding of callbacks: Callbacks in C#

Object reference not set to an instance of an object

I am facing an issue while inserting some items into database in asp.net web service application.
Here is my code ..
public void DoRequestLog(HttpRequest request)
{
string UserAgent = request.Headers["User-Agent"];
string Date = "4/14/2011";//request.Headers["Date"];
string HostIP = request.Headers["Host"];
string URL = request.Headers["Referer"];
string MethodName = request.HttpMethod;
string VersionNo = "";
string IMEINo = "";
string dbString = Configuration.GetDBConnectionString();
SqlConnection DardSqlConnection = new SqlConnection(dbString);
DardSqlConnection.Open();
SqlCommand log = DardSqlConnection.CreateCommand();
log.CommandText = "insert into ConnectionLog values('"+UserAgent+"','"+Date+"','"+HostIP+"','"+URL+"','"+MethodName+"','"+VersionNo+"','"+IMEINo+"');";
log.ExecuteNonQuery();
}
Please Help
Since I am new to .net environment.
Try this:
public void DoRequestLog(HttpRequest request)
{
// We don’t need to log anything if there is no HTTP request.
if (request == null)
return;
string UserAgent = request.Headers["User-Agent"];
string Date = "4/14/2011";//request.Headers["Date"];
...

Resources