I am trying to disable the caching on on the the pages. The reason - the page in question should display up to date data on each request and the data is coming from external XML feed.
I am using standard HttpWebRequest HttpWebResponse. All is working fine but I am getting some (I believe) caching issues where by querying XML feed URL directly I am getting more up to date data compared to my Controller/View data which uses the same URL.
XML feed URL is appended with random numbers on each request and Caching was disabled in the controller ([OutputCache(NoStore = true, Duration = 0)]) as well as in the ActionResult, which produces the following:
Response
HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.1
X-AspNet-Version: 4.0.30319
X-Frame-Options: SAMEORIGIN
X-Powered-By: ASP.NET
X-UA-Compatible: IE=edge
Date: Thu, 04 Aug 2016 13:22:33 GMT
Content-Length: 75285
Request
pretty print
GET /investor-relations/share-price HTTP/1.1
Host: cms.crestnicholson-dev.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: ecos.dt=1470316952533; ASP.NET_SessionId=5lbh4v20kac0boadibjfwedr; IsAgreeToCookiePolicy=true
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
And still outdated/cached data is rendered on the pageā¦
If someone has any ideas/suggestions, It would be greatly appreciated.
Controller code:
[OutputCache(NoStore = true, Duration = 0)]
public class InvestorRelationsController : Controller
{
public ActionResult SharePrice()
{
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
return PartialView(GetSharePrice());
}
private SharePriceModel GetSharePrice()
{
try
{
var xml = GetSharePriceXml();
return ParseSharePrice(xml);
}
catch (Exception)
{
return new SharePriceModel() {IsServiceUnavailable = true};
}
}
private SharePriceModel ParseSharePrice(string xml)
{
Guard.ArgumentNotNull(xml, "xml");
var model = new SharePriceModel();
var doc = new XmlDocument();
doc.Load(new StringReader(xml));
var root = doc.DocumentElement;
model.DateLastUpdated = root.SelectSingleNode("Time").InnerText;
model.Price = root.SelectSingleNode("CurrentPrice").InnerText;
model.Change = root.SelectSingleNode("Change").InnerText;
model.ChangePersentage = root.SelectSingleNode("PercentageChange").InnerText;
return model;
}
private string GetSharePriceXml()
{
Uri address = new Uri(SiteConfiguration.SharePriceFeedUrl);
Random random = new Random();
string url = address + "?random=" + random.Next();
// Set a default policy level for the "http:" and "https" schemes.
HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
HttpWebRequest.DefaultCachePolicy = policy;
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
// Create the web request
var request = WebRequest.Create(url) as HttpWebRequest;
// Set type to POST
request.CachePolicy = noCachePolicy;
request.KeepAlive = false;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Cache-Control", "no-cache");
request.Headers.Add("Cache-Control", "private");
// Get response
using (var response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
using (var reader = new StreamReader(response.GetResponseStream()))
{
// Console application output
return reader.ReadToEnd().Trim();
}
}
}
}
Related
I am consuming an OData Service, I am successfully POSTing my request (using RestSharp) to /$batch endpoint and getting the response. the response header contains
"Content-Type" : "multipart/mixed; boundary=<GUID>"
Body is
--C4254E82B51CFE5BD04201606B9AB7C50
Content-Type: multipart/mixed; boundary=C4254E82B51CFE5BD04201606B9AB7C51
Content-Length: 2221
--C4254E82B51CFE5BD04201606B9AB7C51
Content-Type: application/http; charset=utf-8
Content-Length: 2037
content-transfer-encoding: binary
HTTP/1.1 201 Created
Content-Type: application/json
Content-Length: 1732
location: https://test.api/Event/CarEntries('4003581738')
dataserviceversion: 2.0
etag: W/"datetimeoffset'2021-04-21T00%3A49%3A45Z'"
{ JSON }
--C4254E82B51CFE5BD04201606B9AB7C51--
--C4254E82B51CFE5BD04201606B9AB7C50
Content-Type: application/http; charset=utf-8
Content-Length: 15116
content-transfer-encoding: binary
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 15017
dataserviceversion: 2.0
{ JSON }
--C4254E82B51CFE5BD04201606B9AB7C50--
How do I deserialise and extract the JSON Objects in my C# code? I do not want to invent a Regex pattern (well that is my last resort)
I did try using "Simple.OData.Client" (also a few others) but my request is not 100% compatible with the "Simple.OData.Client".
Also tried extracting using the below code but not necessary give me what I want
var sc = new StringContent(response.Content);
var content = sc.ReadAsStreamAsync().Result;
var streamContent = new StreamContent(content);
streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(response.ContentType);
var provider = streamContent.ReadAsMultipartAsync().Result;
Can someone giveme the best way to extract the Json objects ?
Thanks
Nero
I manage to get this working HttpClient and System.Net.Http.Formatting.Extension
Below is the code
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://service-url/Entity/v1.3/$batch"))
{
request.Headers.TryAddWithoutValidation("Accept", "application/json");
request.Headers.TryAddWithoutValidation("Client-Id", "XXXXXXXXX");
// Add all the headers here
// this is your custom batch request
request.Content = new StringContent("--batch\ncontent-type: multipart/mixed;boundary=changeset\n\n--changeset\ncontent-type: application/http\nContent-Transfer-Encoding: binary\n\nPOST CarEntries HTTP/1.1\ncontent-type: application/json;charset=utf-8\naccept: application/json;\n\n{\n\"RefId\": \"Test\",\n\"Child\": {\n\"ChildId\": \"412000415\"\n}\n}\n--changeset--\n--batch--");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/mixed;boundary=batch"); // This is imporatnt - but please refer to your api documentation
var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var multiPartContent = await response.Content.ReadAsMultipartAsync(); // This is part of the extension
var mixedContent = multiPartContent.Contents.First(); // you will have multiple contents, select the content you want
var data = await mixedContent.ReadAsStringAsync();// read it as string
Regex rg = new Regex(#"\{(.|\s)*\}"); // find the json object from mixed content
var json = rg.Match(data);
return JsonConvert.DeserializeObject<TMessage>(json.Value);
}
}
Hope this helps someone in the future. But still, my goal is to use "Simple.OData.Client" or "Microsoft.OData.Client"
I am using MVC framework to make POST request to OneLogin API to get JWT. I am getting a 401 unauthorized message back at my PostAsync call in the code below.
Error look like following
StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
Cache-Control: no-store, no-cache
Date: Wed, 17 Jun 2020 04:21:23 GMT
Set-Cookie: ol_oidc_canary_30=false; path=/; domain=.onelogin.com
X-Powered-By: Express
Content-Length: 77
Content-Type: application/json; charset=utf-8
}
Am i missing any parameters. I registered my localhost on One login dev account. Is there any setting there i need to update or change?
public async Task<OidcTokenResponse> ProcessToken(string code, string clientSec)
{
string authorityToken = OneLoginAuthorityToken;
var formData = new System.Net.Http.FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("client_id", OneLoginClientID),
new KeyValuePair<string, string>("client_secret", clientSec),
new KeyValuePair<string, string>("grant_type", "authorization_code"),
});
using (var client = new System.Net.Http.HttpClient())
{
const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
const System.Net.SecurityProtocolType Tls12 = (System.Net.SecurityProtocolType)_Tls12;
System.Net.ServicePointManager.SecurityProtocol = Tls12;
var res = await client.PostAsync(authorityToken, formData);
var json = await res.Content.ReadAsStringAsync();
var tokenReponse = Newtonsoft.Json.JsonConvert.DeserializeObject<OidcTokenResponse>(json);
return tokenReponse;
}
}
You need to send the redirect_uri again in this message - it is a security feature of the authorization code flow.
Also worth tracing the messages with a tool such as Fiddler to ensure that the messages sent over the wire are what you'd expect.
See steps 4 and 8 of my messages write up for something to compare against.
I am trying to invalidate a token but I get the following exception:
+ Headers {X-AspNetMvc-Version: 3.0
xoauth_problem: parameter_absent
xoauth_parameters_absent: oauth_session_handle&oauth_token
Connection: keep-alive
Content-Length: 165
Cache-Control: private
Content-Type: text/html; charset=utf-8
Date: Thu, 16 Aug 2012 20:03:38 GMT
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
} System.Net.WebHeaderCollection
Here is the code:
Uri url = new Uri("https://XXXYYY/OAuth/InvalidateToken");
string oauthHeader = "OAuth oauth_session_handle="AAA3D&",oauth_token="SDSFSDSDF%3D",oauth_consumer_key="5512CONSUMER",oauth_nonce="0000012145o",oauth_signature="QEESIGN99$",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1345141023",oauth_version="1.0"";
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
webReq.Method = WebRequestMethods.Http.Get;
webReq.Headers.Add(HttpRequestHeader.Authorization, oauthHeader);
WebResponse response = webReq.GetResponse();
Please note I do have parameters
I'm sending request to the server and I'm getting the html response. But
I want to store the cookie information. Is there any other classes or methods
available to get the cookie information in blackberry.
for (int j = 0; j < 20; j++) {
String key = httpConn.getHeaderFieldKey(j);
String field = httpConn.getHeaderField(j);
if (key == null && j > 0) {
break;
}
add(new RichTextField(key + " : " + field));
}
I used this code to get the header information, but I didnt get-setcookie header ( which I'm supposed to get). the output is as follows.
Connection: Close
expires: -1
date: Tue, 08 Mar 2011..........
server: Microsoft-IIS/7.5
x-powered-by: ASP.NET
pragma:no-cache
x-rim-etag:4626353C5B58791ACD00D30EAADEAF4663FE219F
cache-control: no-cache, no-store
x-aspnet-version:2.0.50727
content-location:http://beemediahive...........
content-type: text/html; charset=utf-8
How do I get cookie information in blackberry?
check out below link:
http://esgroupmobile.wordpress.com/2009/05/29/blackberry-development-tip-http-get/
Hope it helps you.
ASP.Net MVC 3 RTM. I am trying to use the OutputCache attribute in an action, but doesn't appear to be working. Here is the Http Request and Response.
Request URL:http://localhost/MyApp/Employee.mvc/GetImage?userId=myUserId
Request Method:GET
Status Code:200 OK
Request Headers
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Cookie:ASP.NET_SessionId=sessionIdStuff
Host:localhost
Pragma:no-cache
Referer:http://localhost/MyApp/Employee/Review/1/Index
User-Agent:Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US)
AppleWebKit/534.13 (KHTML, like Gecko)
Chrome/9.0.597.98 Safari/534.13
Query String Parameters
userId:myUser
Response Headers
Cache-Control:private, no-store, max-age=3484
Content-Length:1428
Content-Type:image/jpeg
Date:Wed, 16 Feb 2011 22:59:14 GMT
Expires:Wed, 16 Feb 2011 23:57:19 GMT
Last-Modified:Wed, 16 Feb 2011 22:57:19 GMT
Server:Microsoft-IIS/5.1
Vary:*
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0
X-Powered-By:ASP.NET
Here is the controller:
[HttpGet, OutputCache(Location= OutputCacheLocation.Client, VaryByParam="userId", Duration=3600, NoStore=true)]
public FileContentResult GetImage(string userId)
{
byte[] result;
using (var client = new WebClient())
{
client.Credentials = CredentialCache.DefaultCredentials;
result = client.DownloadData(string.Format(IntranetUrl, userId));
}
return File(result, "image/jpeg");
}
and my View:
<img alt="Employee Picture" src='#Url.Action("GetImage", "Employee", new { userId = Model.UserId, area=""})' width="75px" height="100px" />
I tried comparing with other static images that are getting cached and the only differences where these lines:
Cache-Control:private, no-store,
max-age=3484
This is included in my action, but not in the static images. Also, the static images had an ETag, but my action response did not.
Can anyone help why this might not be cached in the browser?
Thanks for any help..
Try remove: NoStore=true (or set NoStore = false), and it'll work :)