MOTOBIT.COMWork with If-Modified-Since and Last-Modified in ASP.Net.

About | IIS monitor | ASP upload | ASP dictionary | UserManager | Pure ASP upload script | Programming tips
Other articles:
Work with binary files in VBSscript - read and write local and remote files (WSH, File & data transfer, Functions, VBScript)
Download multiple files in one http request (File & data transfer, VBScript)
Base64 encode VBS function (vb encoder algorithm), source code (Conversion, VBScript)
Read and write SQL image data, store binary file to sql table. (WSH, Database, Conversion, VBScript)
Do you like this article?
Please, rate it
and write review!
Rated:
by Aspin.com users
What do you think?
Areas > Languages > VB.Net
Areas > ASP / ASP.Net > Functions > http
Sometimes you will need to send static files over http using ASP.Net - for example if you want to control access to the file programmatically. Such tasks can be simply handled by Response.WriteFile(FileName) for plain html files, but there are two problems:
  • Response.ContentType is "text/html" by default. So if you want to write .gif images by ASPX, you have to set right Content-Type http header according to the file type (image/gif).
  • There is a good idea to handle at least Last-Modified and If-Modified-Since headers to reduce traffic and increase performance. Otherways, the file is sent each time.
I created a simple VB.Net support functions for this tasks.
1. GetContentType - returns content-type of a file from registry
2. DateFromHTTP - converts string date from http header (Fri, 09 Sep 2005 07:51:28 GMT format) to Date format
3. DateToHTTPDate - converts date to string format.
  Function SendFileOverHTTP(ByVal FileName) As String
    'Get If-Modified-Since header from request.
    Dim sIfModifiedSince As String = Request.Headers("If-Modified-Since")

    'Convert the header To date.
    Dim IfModifiedSince As Date = DateFromHTTP(sIfModifiedSince)

    'Get a time when the file was last modified.
    Dim LastModified As Date = FileDateTime(FileName).ToUniversalTime

    'round the date To seconds.
    LastModified = New Date(LastModified.Year, LastModified.Month, LastModified.Day, _
      LastModified.Hour, LastModified.Minute, LastModified.Second)

    'Check If the last modified time of the file is greater than If-Modified-Since
    If LastModified > IfModifiedSince Then '200 OK - file was modified.
      Response.StatusCode = "200"
      Response.StatusDescription = "OK"

      'Set Last-Modified header
      Response.AddHeader("Last-Modified", DateToHTTPDate(LastModified))

      Dim ContentType As String = GetContentType(FileName)
      'Set Content-type http header (from registry)
      Response.ContentType = ContentType
      Response.WriteFile(FileName)
      Return "Send: " & FileLen(FileName) & "," & ContentType & "," & FileName
    Else '304 - file is Not modified.
      Response.StatusCode = "304"
      Response.StatusDescription = "Not Modified"
      Return "304: " & LastModified & "," & IfModifiedSince & "," & FileName
    End If
  End Function


'Support functions:

  'returns a content-type of the file by file extensions
  Public Function GetContentType(ByRef FileName As String) As String
    'get the file ext
    Dim Ext As String = System.IO.Path.GetExtension(FileName)

    'open a the file type registry key 
    Dim Reg As Microsoft.Win32.RegistryKey = _
      Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(Ext)

    'read Content Type value.
    Return Reg.GetValue("Content Type")
  End Function


  Public Function GetFileLastModified(ByVal FileName) As String
    Return DateToHTTPDate(FileDateTime(FileName))
  End Function



  'Converts date (19991022 11:08:38)
  'to http form (Fri, 22 Oct 1999 12:08:38 GMT)
  Function DateToHTTPDate(ByVal OleDATE As Date) As String
    On Error Resume Next
    OleDATE = OleDATE.ToUniversalTime
    Return engWeekDayName(OleDATE) & _
     ", " & Right("0" & Day(OleDATE), 2) & " " & engMonthName(OleDATE) & _
     " " & Year(OleDATE) & " " & Right("0" & Hour(OleDATE), 2) & _
     ":" & Right("0" & Minute(OleDATE), 2) & ":" & Right("0" & Second(OleDATE), 2) & " GMT"
  End Function

  Function engWeekDayName(ByVal dt As Date) As String
    Dim Out As String
    Select Case WeekDay(dt, 1)
      Case 1 : Out = "Sun"
      Case 2 : Out = "Mon"
      Case 3 : Out = "Tue"
      Case 4 : Out = "Wed"
      Case 5 : Out = "Thu"
      Case 6 : Out = "Fri"
      Case 7 : Out = "Sat"
    End Select
    Return Out
  End Function

  Function engMonthName(ByVal dt As Date) As String
    Dim Out As String
    Select Case Month(dt)
      Case 1 : Out = "Jan"
      Case 2 : Out = "Feb"
      Case 3 : Out = "Mar"
      Case 4 : Out = "Apr"
      Case 5 : Out = "May"
      Case 6 : Out = "Jun"
      Case 7 : Out = "Jul"
      Case 8 : Out = "Aug"
      Case 9 : Out = "Sep"
      Case 10 : Out = "Oct"
      Case 11 : Out = "Nov"
      Case 12 : Out = "Dec"
    End Select
    Return Out
  End Function

  Public Function DateFromHTTP(ByVal HTTPDate As String) As Date
    Dim Swd As String, d As String, Sm As String, y As String, h As String
    Dim m As String, s As String, g As String, Out As Date
    HTTPDate = LCase$(HTTPDate)

    If Mid$(HTTPDate, 27, 3) = "gmt" Then
      Swd = Left$(HTTPDate, 3)
      d = Mid$(HTTPDate, 6, 2)
      Sm = Mid$(HTTPDate, 9, 3)
      y = Mid$(HTTPDate, 13, 4)
      h = Mid$(HTTPDate, 18, 2)
      m = Mid$(HTTPDate, 21, 2)
      s = Mid$(HTTPDate, 24, 2)
      Out = New Date(y, mFromSm(Sm), d, h, m, s)
      Out = Out.ToLocalTime
    End If

    Return Out
  End Function

  Function wdFromSwd(ByVal Swd As String) As Integer
    Dim Out As Integer
    Select Case LCase$(Swd)
      Case "sun" : Out = 1
      Case "mon" : Out = 2
      Case "tue" : Out = 3
      Case "wed" : Out = 4
      Case "thu" : Out = 5
      Case "fri" : Out = 6
      Case "sat" : Out = 7
    End Select
    Return Out
  End Function

  Function mFromSm(ByVal Sm As String) As Integer
    Dim Out As Integer
    Select Case LCase$(Sm)
      Case "jan" : Out = 1 : Case "feb" : Out = 2
      Case "mar" : Out = 3 : Case "apr" : Out = 4
      Case "may" : Out = 5 : Case "jun" : Out = 6
      Case "jul" : Out = 7 : Case "aug" : Out = 8
      Case "sep" : Out = 9 : Case "oct" : Out = 10
      Case "nov" : Out = 11 : Case "dec" : Out = 12
    End Select
    Return Out
  End Function

See also

for 'Work with If-Modified-Since and Last-Modified in ASP.Net.' article
How to convert http date to OLE(VB/VBS) date.ASP (VBS) function converting http string date (like Fri, 22 Oct 1999 12:08:38 GMT) to DATE data type.
How to convert DATE to a HTTP string date in ASPASP (VBS) function converting DATE data type to http string date (like Fri, 22 Oct 1999 12:08:38 GMT).

Copyright and use this code

The source code on this page and other samples at http://www.motobit.com/tips/ are a free code, you can use it as you want: copy it, modify it, use it in your products, ...
If you use this code, please:
1. Leave the author note in the source.
or
2. Link this sample from you page.
<A
 Href="http://www.motobit.com/tips/detpg_net-last-modified/"
 Title="Short support vb.Net functions to convert
	date from/to http string date
	and sample code to send
	files with 304 http code"
>Work with If-Modified-Since and Last-Modified in ASP.Net.</A>

© 1996 - 2012 Antonin Foller, Motobit Software | About, Contacts | e-mail: info@pstruh.cz


Partner sites: Search Czech Last minute Zajezdy Obsah na mobil Hry na mobil Java Hry Print-shop Affiliate programy

Kurzy: Akcie | Urad prace | Zakony | Zlato | Firmy | Dane


     IISTracer - IIS ISAPI real-time monitor IISTracer is a real-time monitoring tool for Microsoft IIS, which will show/log you what is happenning on IIS server right now. It let's you reveal problems with long-running scripts (.asp, .cgi, cfm...), hang-up states and low resource situations and lets you stop long-running requests (uploads/downloads).      ActiveX User account Manager - Set of simple objects for creating, deleting, and managing user accounts, groups, servers and domains in the Windows NT environment.
     Active log file - Hi-performance text file logging for ASP/VBS/VBA applications. Lets you create daily/weekly/monthly log files with variable number of logged values and extra timing and performance info.      ActiveX windows registry editor - Intuitive, easy to use COM interface to windows registry. Set of classes to read/enumerate/modify windows registry keys and values from ASP, VBS and T-SQL.
     ActiveX/ASP Multi Dictionary object - Free-threaded hi-speed dictionary algorithm with unique/nonunique keys (map/multimap). Connect to another dictionary object in the same process. Lock and Unlock methods to synchronize tasks (application scope). Share ASP Application/Session objects.      Export DBF/MDB from ASP - Conversion from recordset to MDB/DBF. Direct binary output of MDB or DBF files from ASP pages with one row of code.
     Pure-ASP upload - lets you upload files using Pure ASP VBS code (using multipart/form-data and input type=file).      ByteArray - Works with safearray binary data (VT_UI1 | VT_ARRAY) - save/restore binary data from disk, find, work with code pages, convert to string/hexstring(SQL).
     WebChecker - Checks http, https, ftp and gopher internet connections in regular intervals. Lets you monitor web site functionality (uptime). Enables restart or notification on problems.      HTTPLog ISAPI filter - Lets you log incomming/outgoing http header and document data to separate files. Monitor of IIS service input/output.
Motobit.com