In this question's most voted answer there is this line :
cookieJar.Add(new Cookie("my_cookie", "cookie_value", "/", "mysite"));
In this line, there are "my_cookie", cookie_value and "mysite" fields. I don't know how to fill these lines. Can you tell me how to fill those with an example? Thanks in advance.
Hope this Helps
CookieContainer gaCookies = new CookieContainer();
Uri target = new Uri("http://www.google.com/");
gaCookies.Add(new Cookie("__utmc", "#########") { Domain = target.Host });
or head here for more information
Try this:
HttpCookie _cookie = new HttpCookie("Department"); // Create and give name
_cookie.Expires = DateTime.Now.AddDays(30); // expries in one month
_cookie.Value = "Dep1"; // set value
HttpContext.Response.Cookies.Add(_cookie); // add cookie to the context
Related
I tried adding this in the bootstrapper in the ApplicationStartup override.
pipelines.AfterRequest.AddItemToStartOfPipeline(ctx =>
{
ctx.Request.Headers["x-fcr-version"] = "1";
});
Its giving me errors.
Can anyone point me in the right direction?
Notice how you are trying to set the Request while trying to manipulate the Response ?
Try this..
protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
{
base.RequestStartup(container, pipelines, context);
pipelines.AfterRequest.AddItemToEndOfPipeline(c =>
{
c.Response.Headers["x-fcr-version"] = "1";
});
}
This is what my Response looks like..
Or .. you can use Connection Negotiation if you're going to set it at the module level...
Get["/"] = parameters => {
return Negotiate
.WithModel(new RatPack {FirstName = "Nancy "})
.WithMediaRangeModel("text/html", new RatPack {FirstName = "Nancy fancy pants"})
.WithView("negotiatedview")
.WithHeader("X-Custom", "SomeValue");
};
Since this question is about adding headers to a nancy request, which I need to do as I need to add an origin header, and some others when making requests to my app api.
In order to get it to work, I did the following:
//create headers dictionary
var myHeaders = new Dictionary<string, IEnumerable<string>>();
myHeaders.Add("origin",new List<String>{"https://my.app.com"});
//..... snip - adding other headers ....//
var uri = new Uri("https://my.api.com");
var request = new Nancy.Request("OPTIONS", uri, null, myHeaders,"127.0.0.1", null);
I found reading the nancy request source source useful, as the null parameters, (body and protocolVersion) and I passed through get initialized if not set.
For some reason the answer with content negotiation is not working in my case but I found another way:
Get["result"] = x=>
{
...
var response = Response.AsText(myModel, "application/json");
response.Headers.Add("Access-Control-Allow-Origin", "http://example.com");
response.Headers.Add("Access-Control-Allow-Credentials", "true");
return response;
};
All i want to save instance of a class in a cookie just to check something.
Here is my code
class khurram {
khurram k1= new khurram();
HttpCookie tcook = new HttpCookie("test");
tcook.Value = k1;
}
but 'tcook' is not present. what am i doing wrong i don't understand.
i also tried
[serializable]
class khurram {
public string str1{get;set;};
}
khurram k1= new khurram();
HttpCookie tcook = new HttpCookie("test");
tcook.Value = k1;
please help.
thanks in advance
The Value property is defined to be of type string - in both of your examples, you appear to be trying to give it a class khurram
Someething like this may work better for you:
class khurram {
public string str1{get;set;};
}
// later ...
khurram k1= new khurram();
HttpCookie tcook = new HttpCookie("test");
tcook.Value = k1.str1;
HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;
// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);
// Add the cookie.
Response.Cookies.Add(myCookie);
Response.Write("<p> The cookie has been written.");
I have a cookie called SurveyCookie. Created like so:
var cookie = new HttpCookie("SurveyCookie");
cookie.Values["surveyPage"] = "1";
cookie.Values["surveyId"] = "1";
cookie.Values["surveyTitle"] = "Definietly not an NSA Survey....";
cookie.Values["lastVisit"] = DateTime.UtcNow.ToString();
cookie.Expires = DateTime.UtcNow.AddDays(30);
Response.Cookies.Add(cookie);
Which works great. Now the problem comes when I want to change the value "surveyPage" like so.
The below will create a new cookie which is not what I want.
int cookieValue = Convert.ToInt32(Request.Cookies["SurveyCookie"]["surveyPage"]) + 1;
Response.Cookies["SurveyCookie"]["surveyPage"] = cookieValue.ToString();
Then I tried this code below which doesn't work either. The surveyPage is still 1 when it should be 2.
Request.Cookies["SurveyCookie"]["surveyPage"] = cookieValue.ToString();
Since neither of the above works what does change the cookies value for surveyPage?
From ASP.NET Cookies Overview:
You cannot directly modify a cookie. Instead, changing a cookie
consists of creating a new cookie with new values and then sending the
cookie to the browser to overwrite the old version on the client.
You can try this:
HttpCookie cookie = Request.Cookies["SurveyCookie"];
if (cookie == null)
{
// no cookie found, create it
cookie = new HttpCookie("SurveyCookie");
cookie.Values["surveyPage"] = "1";
cookie.Values["surveyId"] = "1";
cookie.Values["surveyTitle"] = "Definietly not an NSA Survey....";
cookie.Values["lastVisit"] = DateTime.UtcNow.ToString();
}
else
{
// update the cookie values
int newSurveyPage = int.Parse(cookie.Values["surveyPage"]) + 1;
cookie.Values["surveyPage"] = newSurveyPage.ToString();
}
// update the expiration timestamp
cookie.Expires = DateTime.UtcNow.AddDays(30);
// overwrite the cookie
Response.Cookies.Add(cookie);
You should always create a new cookie each time you need to modify an existing one , the following works for me :
var cookie = new System.Web.HttpCookie("SurveyCookie");
cookie.Values["surveyPage"] = newValue;
cookie.Expires = DateTime.Now.AddDays(1000);
cookie.SameSite = System.Web.SameSiteMode.None;
cookie.Secure = true;
this.HttpContext.Response.Cookies.Add(cookie);
Check out the Response.SetCookie() method as this will set update your existing cookie
Hi I am creating a cookie in the following way:
HttpCookie cookie = new HttpCookie("CookieNameHere");
cookie.Values["test1"] = "Value1";
cookie.Values["test2"] = "Value2";
cookie.Values["test3"] = "Value3";
//I have also tried cookie.Values.Add("test1", "Value1");
cookie.Expires = DateTime.Now.AddDays(365d);
HttpContext.Current.Response.AppendCookie(cookie); //here I have also tried HttpContext.Current.Response.Cookies.Add(cookie);
but when I read out the cookie using the following code:
HttpCookie cookie = new HttpCookie("CookieNameHere");
cookie = HttpContext.Current.Response.Cookies["CookieNameHere"];
I always get that the cookie.Values is empty
Is there something I am doing wrong here?
Normally you would write the cookie in a Response, and then read it from subsequent Requests.
I see you're trying to read it from the Response - is this within the context of the same HTTP request, or just a typo?
Try
HttpCookie cookie = HttpContext.Current.Request.Cookies["CookieNameHere"];
You have to ask for those Cookies in a Request.
HttpCookie cookie = Request.Cookies["CookieName"];
Any idea of how to upload a file to Google site from c#?
I am trying to upload but getting a 403 error. However, I am using the same credentials to connect to the site and get the list of attachments and pages present on the site.
Any help would be greatly appreciated!!
They most likely have an anti-CSRF scheme that stores temporal identifiers in the page and/or cookies, this is specifically to hinder bots.
You are most likely submitting a request without the proper CSRF tokens and get rejected. I would recommend analyzing how they handle CSRF, after this point it will most likely boil down to making a WebRequest to the page and so you can get any cookies they get back, along with having the form so you can scrape out any hidden fields that are relevant. Then move those over to your post request that you're attempting to the send the file to.
I figured out the problem and resolved it. Below is the complete function:
public bool UploadAttachment()
{
try
{
//AsyncSendData data = new AsyncSendData();
string parentUrl = Cabinets["Cabinet1"].ToString();
string parentID = parentUrl.Split('/')[7];
AtomEntry entry = new AtomEntry();
entry.Title.Text = "abc.jpg";
AtomCategory cat = new AtomCategory();
cat.Term = ATTACHMENT_TERM;
cat.Label = "attachment";
cat.Scheme = KIND_SCHEME;
entry.Categories.Add(cat);
AtomLink link = new AtomLink();
link.Rel = PARENT_REL;
link.HRef = parentUrl;
entry.Links.Add(link);
AtomContent content = new AtomContent();
FileInfo info = new FileInfo("C:\\Bluehills.txt");
FileStream stream = info.Open(FileMode.Open,FileAccess.ReadWrite,FileShare.ReadWrite);
this.setUserCredentials(userName, password);
Uri postUri = new Uri(makeFeedUri("content"));
entry.Source = new AtomSource();
//this.EntrySend(postUri, entry, GDataRequestType.Insert);
// Send the request and receive the response:
AtomEntry insertedEntry = this.Insert(postUri, stream, (string)DocumentTypes["TXT"], "bluehills");
return true;
}
catch (Exception ex)
{
return false;
}
}