Question

For the purposes of user tracking, I have an etagged javascript snippet which i return from a .aspx page.

The relevant code is below:

string eTag = this.Request.Headers["If-None-Match"];

if (eTag != null)
{
    Response.StatusCode = 304;
    Response.SuppressContent = true;  
}
else
{
    string data = "asdfasdfs";
    string script = "(function(){DoSomething('" + data + "');})();";

    Response.ContentType = "application/javascript"; 
    Response.Cache.SetLastModified(DateTime.Now);
    Response.Cache.SetCacheability(HttpCacheability.Public);
    Response.Cache.SetETag(data);
    Response.Write(script);
}

I have converted this project to an MVC WebAPI2 (VS 2013) project, but I'm not sure exactly how to achieve the same functionality.

If this was a full MVC project I could create a custom ActionResult like in this example: http://blogs.microsoft.co.il/alon_nativ/2011/07/10/aspnet-mvc-imagepixel-actionresult/ . But, WebAPI methods do not normally return an ActionResult.

I believe I could use HttpResponseMessage - http://msdn.microsoft.com/en-us/library/system.net.http.httpresponsemessage(v=vs.110).aspx, but this class appears to be missing several things from the code above.

What is the cleanest/best practice way to do this in WebAPI?

Was it helpful?

Solution

I was able to individually track down each item, appears to be working.

Hope this helps someone in the future.

HttpResponseMessage response = null;

var eTag = Request.Headers.IfNoneMatch;

if (eTag != null && eTag.Count > 0)
{
    response = Request.CreateResponse(HttpStatusCode.NotModified);
}
else
{
    string data = "asdfasdfs";

    string script = "(function(){DoSomething('" + data + "');})();";

    response = Request.CreateResponse(HttpStatusCode.OK);

    response.Content = new StringContent(script, Encoding.UTF8, "application/javascript");
    response.Content.Headers.LastModified = DateTime.Now;
    response.Headers.CacheControl = new CacheControlHeaderValue() { Public = true };
    response.Headers.ETag = new EntityTagHeaderValue("\"" + data + "\"");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top