In my asp.net mvc 2 app, I'm wondering about the best way to implement this:
For every incoming request I need to perform custom authorization before allowing the file to be served. (This is based on headers and contents of the querystring. If you're familiar with how Amazon S3 does rest authentication - exactly that).
I'd like to do this in the most perfomant way possible, which probably means as light a touch as possible, with IIS doing as much of the actual work as possible.
The service will need to handle GET requests, as well as writing new files coming in via POST/PUT requests.
The requests are for an abitrary file, so it could be:
GET http://storage.foo.com/bla/egg/foo18/something.bin
POST http://storage.foo.com/else.txt
Right now I've half implemented it using an IHttpHandler which handles all routes (with routes.RouteExistingFiles = true), but not sure if that's the best, or if I should be hooking into the lifecycle somewhere else?
I'm also interested in supporting partial downloads with the Range header. Using
response.TransmitFile(finalPath);
as I am now means I'll have to do that manually, which seems a bit lowlevel?
Many thanks for any pointers.
(IIS7)
I think having a custom handler in the middle that takes care of this is exactly how you should be doing it.
TransmitFile is the lightest-weight programmatic way to serve a file that I am aware of.
However, you might not need to write your own HttpHandler. You can use the MVC handler and just dedicate a controller action to the job. Something like:
http://storage.foo.com/Files/Download/SomeFileIdentifier
...routing to...
public FilesController
{
public ActionResult Download(string id)
{
//...some logic to authenticate and to get the local file path
return File(theLocalFilePath, mimeType);
}
}
The File() method of controller uses TransmitFile in the background, I believe.
(PS, If you want shorter URLs, do it via custom routes in global.asax.)
Related
How can i return html content with Google Cloud Endpoints using JAVA?
I'd like to return an html page after a user call a REST API. It is possible?
Endpoints aren't designed to return web pages. You can look at endpoints as a framework for defining remote procedures or a RESTful API. i.e. something you'd call from JS or a mobile platform. To serve a web page on App Engine in Java you should use an App Engine servlet similar to this example.
You can return it as a string, assuming you had cached the HTML page somewhere accessible (remember, appengine has no local file storage). Within your endpoints function, you can access datastore, memcache, cloudstorage, etc...
While I do echo the other poster in saying this is not the use-case endpoints is really meant to target, the point is, endpoints is a great way to make an API with automatic generation of client libraries for multiple platforms. Do use endpoints for your API, but be sure it's an API function and not just HTML file serving, for which there are better patterns.
If you are using this pattern to serve HTML partials for an ajax-style dynamic-replacement div in a web app, this is fine, although if these partials are not needing processing or can be defined at deployment time, rather than being put() and get()'d from datastore, for example, then it's best to simply link them in as static resources using the appengine-web.xml / app.yaml (depending on java or python/go/php)
I hope this has helped you think more about your use-case.
You can redirect browser to new page after server responded to call:
gapi.client.yourapp.yourmethod().execute(function(resp) {
console.log(resp);
if (resp.page){
location = 'http://yourappid.appspot.com/' + resp.page + '?userid=123';
}
});
But you must take care somehow about not losing your context. For example transfer userid as done in above code.
Is it possible to access HttpContext.Current.Session through a WebAPI ? can we make it inheriting IRequiresSession?
I have a generic handler doing a Session set after an API call which I want to remove.
public void AccountController : ApiController, IRequiresSessionState
{
public void Login()
{
setsession(){}
}
}
Technically, yes, although I'd really advise against this practice - a REST API should be completely stateless (cookies and other client-side state is OK).
If you absolutely must do this, you can grab the HTTP context like so:
var context = Request.Properties["MS_HttpContext"] as HttpContext;
At which point you just use its Session property to get the session.
Note that this breaks certain contracts assumed by System.Net.Http - specifically it means your API controllers can never be self-hosted because they're coupled to ASP.NET. If you're OK with this, and with the fact that your API controllers may not work properly from a web farm unless you re-architect everything to use distributed sessions - well then, go for it.
P.S. It is also possible to use IRequiresSessionState, but you can't use it on the controller itself, you need to use it on an HttpControllerHandler and set it as the RouteHandler. The approach is discussed in this MSDN thread. Again, I can't recommend strongly enough against this idea, it violates the basic principle of a Web API - but, if you've got a really good reason for it, then it's another option which is a bit more reusable.
Casting it as HttpContext did not work for me using Web Api 2.1. However I could use HttpContextWrapper.
var context = Request.Properties["MS_HttpContext"] as HttpContextWrapper;
Yes - although not recommended. Here's a working answer based on the answers above (for WebAPI version 2.x)
var context =(HttpContextWrapper)Request.Properties["MS_HttpContext"];
var sessionId = context.Request.Params["ASP.NET_SessionId"];
Hey, I created a HttpHandler for downloading files from the server. It seems it is not handling anything...I put a breakpoint in the ProcessRequest, it never goes there.
public class DownloadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//download stuff and break point
}
}
It never stops there, as mentioned. I also registered it in the web.config.
<add verb="*" path="????" type="DownloadHandler" />
I am not sure about the path part of that entry. What do I have to enter there? I am downloading txt files, but the URL does not contain the filename, I somehow have to pass it to the handler. How would I do this? Session maybe?
Thanks
Have you read How to register Http Handlers? Are you using IIS 6 or 7?
The path part should contain a (partial) url, so if in your case you are using a static url without the filenames, you should put that there. You can end the url in the name of a non-existent resource and map that to path
e.g. the url is http://myserver.com/pages/downloadfiles
and the path="downloadfiles"
If you do POST, you can put the filename in a hidden field, and extract it in the handler. If you're using GET, I'm not sure, either cross-post the viewstate or put the filename in the session like you said.
Any reason why you can't put the filename in the url?
The path for a handler needs to be the path you are trying to handle - bit of a tautology I know but it's as simple as that. Whatever path on your site (real or much more likely virtual) you want to be handled by this handler.
Now unless the kind of file at the end of that path is normally handled by ASP.NET (e.g. .aspx, .asmx but not a .txt) ASP will never see the request in order for it to go through it's pipeline and end up at your handler. In that case you have to bind the extension type in IIS to ASP.NET.
As far as identifying what file the handler is supposed to respond with you could achieve this any number of ways - I would strongly recommend avoiding session or cookies or anything temporal and implicit. I would instead suggest using the querystring or form values, basically anything which will show up as a request header.
Fianlly, I have to ask why you're using a handler for this at all - .txt will serve just fine normally so what additional feature are you trying to implement here? There might well be a better way.
I need to implement a custom handler for MVC that gives me the first look at URLs requests to determine if it should rewrite the urls before submitting the URL to the routing engine. Any pattern is a candidate for the redirect, so I need to intercept the URL request before the standard MVC routing engine takes a look at it.
After looking at a whole bunch of examples, blogs, articles, etc. of implementing custom routing for ASP.NET MVC, I still haven't found a use-case that fits my scenario. We have an existing implementation for ASP.NET that works fine, but we're returning the "standard" handler when no overrides are matched. The technique we're currently using is very similar to that described in this MSDN article: http://msdn.microsoft.com/en-us/library/ms972974.aspx#urlrewriting_topic5 which says "the HTTP handler factory can return the HTTP handler returned by the System.Web.UI.PageParser class's GetCompiledPageInstance() method. (This is the same technique by which the built-in ASP.NET Web page HTTP handler factory, PageHandlerFactory, works.)".
What I'm trying to figure out is: how can I get the first look at the incoming request, then pass it to the MVC routing if the current request doesn't match any of the dynamically configured (via a data table) values?
You would need to:
Not use the standard MapRoute extension method in global.asax (this is what sets up the route handler).
Instead, write your own route subtype, like this.
Although I explained to Craig I may not need to override scenario any more (favoring the future rather than the past), I realized there is an easy and reasonably clean place this override could be implemented - in the Default.aspx code behind file. Here's the standard Page_Load method:
public void Page_Load(object sender, System.EventArgs e)
{
// Change the current path so that the Routing handler can correctly interpret
// the request, then restore the original path so that the OutputCache module
// can correctly process the response (if caching is enabled).
string originalPath = Request.Path;
HttpContext.Current.RewritePath(Request.ApplicationPath, false);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
HttpContext.Current.RewritePath(originalPath, false);
}
As you can see, it would be very easy to stick a url processing interceptor in front of the MVC handler. This changes the standard default page behavior and would need to be reflected in any other MVC app you'd want to create with this same method, but it sure looks like it would work.
How would I generate a proper URL for an MVC application to be included in an e-mail?
This is for my registration system which is separate from my controller/action. Basically, I want to send an email verification to fire an Action on a Controller. I don't want to hardcode the URL in, I would want something like the Url property on the Views.
In your Controller, the UrlHelper is just called "Url" - so:
void Index() {
string s = this.Url.Action("Index", "Controller");
}
The "this" is unnecessary, but it tells you where this Url variable comes from
I used:
Html.BuildUrlFromExpression<AccountController>(c=>c.Confirm(Model.confirmedGUID.Value))
It is part of the HTMLHelper (I think in the MVC Futures) so you may have to pass an instance of the HTMLHelper to your service layer, not sure. I use this directly in my view which renders to an email. That gives you the absolute URL and then I store the domain (http://www.mysite.com) in the config file and append it before the URL.
You should probably make the URL part of the configuration of your application.
I know you can do stuff with e.g. the Server property on your web application, but the application will never know if its IP or domain name is reachable from the outside as it might be hidden behind a proxy or a load balancer.
If I'm reading the question correctly, you need to controller/action outside the MVC code. If so, you will need to simply configure the URL in Application Configuration or some such place, unless you have access to the controller classes and use reflection to get the names.