I need to be able to serve audio files to an mvc app while preventing direct access. Ideally the page would render with a player control so the user can start/stop the audio linked to the database record (audio files are in a folder not the db). I have a controller action like this:
Response.Clear();
Response.ContentType = "audio/wav";
Response.TransmitFile(audioFilename);
Response.End();
return Response;
and the view uses the RenderAction method
<% Html.RenderAction("ServeAudioFile"); %>
this works but it won’t display inline on the existing view, it opens a new page with just the media control. Am I totally barking up the wrong tree or is there a way to embed the response in the existing view? works exactly as I would like but I can’t control access to the file.
Your controller action looks very strange, one would say classic WebForms code, not ASP.NET MVC. Normally controller actions return
ActionResult:As far as embedding the player inline inside the browser you may take a look at the
<object>tag and point the url to this controller action (don’t useHtml.RenderAction). And here’s another example of using theobjecttag.As far as preventing direct access is concerned this is not possible, the music file is played on the client and if you prevent access to it you won’t be able to play it. It is the same as trying to hide the HTML of your site. This simply is something that shouldn’t be done. On the other hand you could allow only authenticated users to access this controller action by decorating it with the
[Authorize]attribute.