How to set custom cache response headers for virtual paths? - c#

We have a virtual URL, /bundles. We want to be able to check, at some point during the .NET lifecycle, if the url starts with /bundles and then set headers. We've thought about using HttpCachePolicy Class and using setCacheability and setMaxAge. I'm wondering how we can apply that to any file served via the /bundles route? Where is the best place to handle this?

Sounds like you want a "different" caching behavior for this Route.
I assume that you have a special Controller for this Route.
If so then you could use the OutputCache Attribute on your Action Methods inside the Controller.
[OutputCache(Duration=[InSeconds], ...)]
public ActionResult YourMethod()
{
...
}
this will result in using the ASP.NET Cache Framework.
Optional: You could use a Profile which you set in the IIS WebSite Konfiguration, then you would have to use the Attribute with the Profile Parameter.
[OutputCache(Profile="YOUR_PROFILE")
IIS will add the associated Response Headers like Expire / Cache-Control / Last-Modified...
Also you would gain the Output Cache Feature which is a performance boost.
But if you want to get "full" Control over your Response Headers then you have to create an own IIS Handler where you override the Output Methods.
Because if you have an enabled Dynamic Compression, then the IIS will remove all Response Headers during ASP.NET lifecyle and add "needed" Response Headers after Compression which happens after ASP.NET processes.
Somewhere on the MSDN is a visualization of the IIS Cache Tiers. But you have to make a "deep" search on the MSDN. I would give you a link but that will take a longer time.. ;)

Related

How to place session ID into GET parameter of HTTP request instead of URL in cookieless mode?

I want to use an approach which phpbb uses
(with it's PHP Session ID passed as GET parameter of HTTP request,
like http(s)://server/page.php?sid=somestring
).
PHP generates id that is 26 characters long and
ASP.NET generates one that is 24 characters long
ASP .NET changes/rewrites URL instead, what I want to avoid
How it is implemented in ASP .NET ( https://msdn.microsoft.com/en-us/library/aa479314.aspx ):
Web.Config contains something similar to
<sessionState
cookieless="AutoDetect"
sessionIDManagerType="NyNamespace.MyCustomSessionManager, \
CustomAssemblyNameInBinFolder"
>
</sessionState>
Request is processed by MyCustomSessionManager (derived from ISessionIDManager)
with GetSessionID method (which uses Validate method internally)
obtained ID is used within framework (it's not important for now - how exactly)
...
during rendering code uses Response.ApplyAppPathModifier method
which check Session.IsCookieless property, and modifies URL if user disabled cookies.
generated page with modified URLs is sent to browser
http://yourserver/folder/(session ID here)/default.aspx
I don't want to use these scary URLs.
I am aware about 3 problems with cookieless approach:
ability to publish URL with session ID (I will protect from this with fingerprinting and timestamping)
ability to connect from different tabs of browser into same session (it can be solved later)
some people refers to HTTP standarts and says that these standarts prohibit using GET and POST parameters at the same time. (I have different understanding of there RFCs - it is possible to use any parameters in URI in addition to POST parameters, so I will use both types of parameters at the same time)
I want to do following:
Modify MyCustomSessionManager to extract Session ID from GET parameter of reqiest, instead of URL part
generate 26-characters ID based on digital fingerprint (to be able to verify it later) instead of default one
use Response.Filter to replace/patch URLs to id-in-get-parameter in output as in
http://www.drdobbs.com/windows/post-processing-the-output-of-aspnet-pag/212001499
Additionally I want to override ApplyAppPathModifier on HttpResponse (which is sealed,
but there is HttpResponseWrapper class).
But I don't know when to replace response to response wrapper.
Is this viable approach?
There are several similar questions:
Cookieless session from URL to QueryString
Use Session ID from supplied parameter instead of default behavior in ASP.NET MVC3
And some which I can't find again
I am asking mine, because I don't understood exactly,
how to implement writing of session ID into GET parameter of HTTP request.

How should I handle users browsing to pages in my site meant only for AJAX? Should I ever use GET?

Similar questions have been asked about the nature of when to use POST and when to use GET in an AJAX request
Here:
What are the advantages of using a GET request over a POST request?
and here: GET vs. POST ajax requests: When and how to use either?
However, I want to make it clear that that is not exactly what I am asking. I get idempotence, sensitive data, the ability for browsers to be able to try again in the event of an error, and the ability for the browser to be able to cache query string data.
My real scenario is such that I want to prevent my users from being able to simply enter in the URL to my "Compute.cshtml" file (i.e. the file on the server that my jQuery $.ajax function posts to).
I am in a WebMatrix C#.net web-pages environment and I have tried to precede the file name with an underscore (_), but apparently an AJAX request falls under the same criteria that this underscore was designed to prevent the display of and it, of course, breaks the request.
So if I use POST I can simply use this logic:
if (!IsPost) //if this is not a post...
{
Response.Redirect("~/") //...redirect back to home page.
}
If I use GET, I suppose I can send additional data like a string containing the value "AccessGranted" and check it on the other side to see if it equals this value and redirect if not, but this could be easily duplicated through typing in the address bar (not that the data is sensitive on the other side, but...).
Anyway, I suppose I am asking if it is okay to always use POST to handle this logic or what the appropriate way to handle my situation is in regards to using GET or POST with AJAX in a WebMatrix C#.net web-pages environment.
My advice is, don't try to stop them. It's harmless.
You won't have direct links to it, so it won't really come up. (You might want your robots.txt to exclude the whole /api directory, for Google's sake).
It is data they have access to anyway (otherwise you need server-side trimming), so you can't be exposing anything dangerous or sensitive.
The advantages in using GETs for GET-like requests are many, as you linked to (caching, semantics, etc)
So what's the harm in having that url be accessible via direct browser entry? They can POST directly too, if they're crafty enough, using Fiddler "compose" for example. And having the GETs be accessible via url is useful for debugging.
EDIT: See sites like http://www.robotstxt.org/orig.html for lots of details, but a robots.txt that excluded search engines from your web services directory called /api would look like this:
User-agent: *
Disallow: /api/
Similar to IsPost, you can use IsAjax to determine whether the request was initiated by the XmlHttpRequest object in most browsers.
if(!IsAjax){
Response.Redirect("~/WhatDoYouThinkYoureDoing.cshtml");
}
It checks the request to see if it has an X-Requested-With header with the value of XmlHttpRequest, or if there is an item in the Request object with the key X-Requested-With that has a value of XmlHttpRequest.
One way to detect a direct AJAX call is to check for the presence of the http_referer header. Directly typed URLs won't generate a referrer, but you still won't be able to differentiate the call from a simple anchor link.
(Just keep in mind that some browsers don't generate the header for XHR requests.)

How to rewrite urls such as example.com/1Bta62 to example.com/view.aspx?id=1Bta62 whilst the user still sees example.com/1Bta62?

As part of an url shortening service, I need users to be able to go to an url such as example.com/1Bta62 and end up at example.com/view.aspx?id=1Bta62 whilst the example.com/1Bta62 is maintained in their browser address bar. How can this be done?
I am using a windows server (project is C# ASP.NET); I would prefer to not have to use scripts (i.e. just something in web.config would be great) but welcome answers of any method. The url endings such as the one above 1Bta62 are dynamically generated.
Thanks in advance!
Edit: Has anyone actually managed/knows how to do this with the web.config file - I think it can be done?
I would recommend Url Rewrite Module, which has been designed to do just that. It's an IIS module that requires no changes to be done to the app.
IIS URL Rewrite 2.0 enables Web administrators to create powerful
rules to implement URLs that are easier for users to remember and
easier for search engines to find. By using rule templates, rewrite
maps, .NET providers, and other functionality integrated into IIS
Manager, Web administrators can easily set up rules to define URL
rewriting behavior based on HTTP headers, HTTP response or request
headers, IIS server variables, and even complex programmatic rules. In
addition, Web administrators can perform redirects, send custom
responses, or stop HTTP requests
Update:
Take a look at RouteMagic:
http://haacked.com/archive/2011/01/30/introducing-routemagic.aspx
Please try registering the routes in area registration. For e.g.,
context.MapRoute(
"Myproject_default",
"Myproject/{controller}/{action}/{id}",
new { controller = "Myproject", action = "index", id = UrlParameter.Optional }
);

CacheDuration in WebMethod ignored

I try to cache a webmethod of a webservice. By following the documentation, I have tried to add the CacheDuration attribute, and made a test :
[WebMethod(CacheDuration = 180)]
public int TestCacheDuration()
{
return new Random().Next();
}
For each call of the webmethod, I have a different response, so it is not cached.
Is it normal ?
Thanks for your answers!
This is clearly explained in MSDN forums:
There are two issues that can affect output caching in an ASP.NET 2.0
Web service application.
In ASP.NET 2.0 the HTTP method of the test page has changed from GET
to POST. However, POSTs are not normally cached. If you change the
test page in an ASP.NET 2.0 Web service application to use GET,
caching works properly.
In addition, HTTP indicates that a user agent (the browser or calling
application) should be able to override server caching by setting the
"Cache-Control" to "no-cache". ASP.NET applications, therefore, ignore
cached results when they find a "no-cache" header.
and also:
Use protocols element under webSerices element in web.config:
http://msdn2.microsoft.com/en-us/library/ms228319(VS.85).aspx
source: http://social.msdn.microsoft.com/forums/en-US/asmxandxml/thread/3765f1e2-0ff5-4840-afa2-e85b3d909cd1

MVC C# custom MvcRouteHandler - How to?

Does anyone have experiences in providing a custom MvcRouteHandler? In my application I'd like to implement a globalization-pattern like http://mydomain/en/about or http://mydomain/de/about.
As for persistance, I'd like to have a cookie read as soon as a request arrives and if there is a language setting in this cookie apply it (so a user arriving at http://mydomain/ would be transferred to http://mydomain/en/ for example). If there is no cookie present, I'd like to get the first language the browser supports, apply this one and store it in this cookie.
I guess this can't be done with the standard routing mechanism mvc provides in it's initial project template. In a newsgroup I got the tip to have a look at the MvcRouteHandler and implement my own. But its hard to find a sample on how to do that.
Any ideas?
I don't believe a custom route handler is required for what you are doing.
For your "globalized" URIs, a regular MVC route, with a constraint that the "locale" parameter must be equal to "en", "de", etc., will do. The constraint will prevent non-globalized URIs from matching the route.
For a "non-globalized" URI, make a "catch-all" route which simply redirects to the default or cookie-set locale URI.
Place the "globalized" route above the "catch-all" route in Global.asax, so that "already-globalized" URIs don't fall through to the redirection.
You would need to make a new route handler if you want a certain URI pattern to trigger something that is not an action on a controller. But I don't think that's what you're dealing with, here.
You should be able to do this with ASP.NET MVC's default template, I'm doing something similar. Just build your routes as {language}/{controller}/{action}/{id}
Just set a default route that goes to a controller that checks for the language cookie, and redirects the user based on that cookie.

Categories

Resources