DonutOutputCache not working for an image - asp.net-mvc

I have an ASP.NET MVC controller action like the following:
[HttpGet]
[DonutOutputCache(CacheProfile = "banner")]
public async Task<ActionResult> Banner(string name, string size = "lg")
{
// snipped - work out which banner to show today.
return File(thePathToSomeBannerImageFile, "image/jpeg");
}
And the configuration file looks like:
<caching>
<outputCacheSettings>
<outputCacheProfiles>
...
<add name="banner" duration="31536000" varyByParam="*" />
...
</outputCacheProfiles>
</outputCacheSettings>
</caching>
Since adding DonutOutputCache the image that I used to render to my browser now won't load. I can see in the Fiddler trace that a largish binary file is getting to the browser, but I can't seem to get it to render.
Removing the DonutOutputCache makes the image appear again.
I've tried clearing the cache etc. Any ideas?

Ah, just figured it out from this link: Doesn't work w/ Files?.
Basically DonutOutputCache uses ContentResult internally which works only with text-based content. Since I'm returning a binary response in a FileResult it messes stuff up. Fortunately it works side-by-side with the built in OutputCache, so I could modify my action as follows and it works as expected. I really only needed DonutOutputCache for other bits of my site that are text-based. I tripped myself up trying to just have one caching attribute to rule them all.
[HttpGet]
[OutputCache(CacheProfile = "banner")]
public async Task<ActionResult> Banner(string name, string size = "lg")
{
}

Related

MVC - FileContentResult sends corrupted pdf

I have a simple action method that returns a PDF document, that gets shown in an <iframe> with an <embed> tag, and every few calls to this method will return a corrupted PDF. (I've determined its corrupted by using dev tools to save the response from the server)
Action Method:
public FileContentResult GetPdfReport(string Id)
{
Response.AppendHeader("Content-Disposition", "inline; filename=report.pdf");
var content = System.IO.File.ReadAllBytes(Server.MapPath("~/Reports/Testfile.pdf"));
System.IO.File.WriteAllBytes(Server.MapPath("~/Reports/debugReport.pdf"), content);
return File(content, "application/pdf");
}
View Content:
<embed id="widgetResponsePdf" src="#Url.Action("GetPdfReport", "WidgetResponse", new { Id = "123" })" type="application/pdf" onmouseout="mouseOutHandler();" />
The files TestFile.pdf and debugReport.pdf open just fine when I get a corrupted PDF, and there is no difference in the request and response header between the normal request/response and the corrupted request/response.
Is there some setting in IIS that I am missing that could be causing the inconsistent behavior between requests, or could this be caused solely by a network issue?
In our case, the IFrame has a src attribute that points to a partial view that loads the <embed> content, which then has a src attribute that points to the actual PDF file instead of a PartialView that returns a FileContentResult. The example below has been simplified from our actual implementation
Partial View
<iframe> <!-- iframe is actually loaded from another partial view, it is show here to simplify things -->
<embed
src='#Url.Content(Model.ReportFileName)'
type="application/pdf">
</embed>
</iframe>
Controller
public PartialView GetPdfReport(string Id)
{
var model = PDFResponseModel
{
ReportFileName = Server.MapPath("~/Reports/Testfile.pdf")
};
return PartialView(model);
}
Due to a site restriction for IE support, our users (intranet site) are required to have AdobeAcrobat installed to view PDF's. While this solution works for us, this may not be desirable for internet facing websites.

MVC Blank JsonResult

I'm returning a JsonResult as part of an Orchard CMS Site (MVC 4) and it suddenly stopped working (specifics below).
Here is an example from my controller:
public JsonResult GetStartDate()
{
//a previous version of this question was different here
var startDate = _Settings.DateOpen.GetValueOrDefault(DateTime.MaxValue);
if (startDate < DateTime.Now)
startDate = DateTime.Now;
var start = new
{
year = startDate.Time.Year,
month = (startDate.Time.Month - 1)
};
return Json(start, JsonRequestBehavior.AllowGet);
}
It should be returning actual data. I have verified that the action is being hit and that "start" contains the correct data before being passed into the Json method.
If I navigate directly to the URL, I get a blank white screen.
Inspecting the result of an AJAX request shows that the call fails, the response body is an empty string , the status is "parsererror" and the actual error throws is "SyntaxError: Unexpected end of input."
POST requests work for some reason, this issue only applies to GETs.
This problem is with all JSON GETs, not just any specific method.
What could be affecting the data between the Json method and the client receiving the response?
By default all MVC methods are cached. This can lead to issues during the change/debug cycle. For starters you can turn off caching during development using the decorator below.
[OutputCache(NoStore = true, Duration = 0)]
public ActionResult MyMethod()
You may want to wrap all methods with a caching scheme that is defined in the web.config. This allows caching to be controlled via one configuration change which comes in handy during development.
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<clear />
<add varyByParam="*" duration="0" name="MyCachePlan" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
And use the following decorator:
[OutputCache(CacheProfile = "MyCachePlan")]
public ActionResult MyMethod()

Why doesn't my action method time out?

I have the following controllers:
[TimeoutFilter]
public abstract class BaseController: Controller
{
}
public class IntegrationTestController : BaseController
{
[HttpGet]
public ActionResult TimeoutSeconds()
{
return Content(HttpContext.Server.ScriptTimeout.ToString(CultureInfo.InvariantCulture));
}
[HttpGet]
public ActionResult ForceTimeout()
{
var timeoutWindow = TimeoutFilter.TimeoutSeconds;
Thread.Sleep((timeoutWindow + 5) * 1000);
return Content("This should never get returned, mwahahaaa!");
}
}
For my test scenario I use a config setting of 5 seconds in the TimeoutFilter, and I know this is working because when my test calls TimeoutSeconds, I get the correct value of 5, but when the test calls ForceTimeout, I get an HTTP response of 200 and my 'never returned' text.
And the filter:
public class TimeoutFilter : ActionFilterAttribute
{
internal const string TimeoutSecondsSettingsKey = "MvcActionTimeoutSeconds";
internal static int TimeoutSeconds;
public TimeoutFilter()
{
TimeoutSeconds = int.Parse(ConfigurationManager.AppSettings[TimeoutSecondsSettingsKey]);
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.ControllerContext.HttpContext.Server.ScriptTimeout = TimeoutSeconds;
base.OnActionExecuting(filterContext);
}
}
I could not get this to work by setting the ScriptTimeout property either, even when setting the debug="false" in the web.config as suggested by user Erik Funkenbusch:
<configuration>
<system.web>
<compilation debug="false" targetFramework="4.5"/>
...
It continued to return the text "This should never get returned" rather than timing out during the Thread.Sleep.
It is also worth noting that I also extended the Thread.Sleep to well beyond the Server.ScriptTimeout default of 110 seconds but it still eventually returned the same text rather than timing out.
I then instead tried to set executionTimeout in the web.config:
<configuration>
<system.web>
<httpRuntime targetFramework="4.5" executionTimeout="5"/>
...
If you were to now add a breakpoint to the TimeoutFilter you will observe that the ScriptTimeout value has been set to the executionTimeout value from web.config. Alas, this still did not work for me (regardless of whether debug="false").
I then came across this link about ScriptTimeout and executionTimeout not working with a similar setup to what you describe. The first reply in the post describes using the debug="false" and also mentions that the timeout will have a delay of 5 to 15 seconds. I still had no luck even when using a large Thread.Sleep value. The second reply in this article suggests that the executionTimeout config setting is a replacement of the ScriptTimeout property (which is apparently a COM interface used in classic ASP). This reply suggests that is not possible to set a specific timeout without using your own time-out logic.
Further, I then came across the following (more recent) link where the first reply suggests that the timeout is switched off in MVC. A further reply suggests that this is because an MVCHandler (which selects the controller that will handle the HTTPRequest) is an IHttpAsyncHandler and as it may therefore be executing another request (which is the point of using an async request) it therefore internally switches the time-out state off (this is what I gather from reading this link). It must work with straight asp.net though as using ScriptTimeout seems to be the accepted way in this answer.
The link suggests that adding the following line will allow it to work (but not in a medium trust application):
System.Web.HttpContext.Current.GetType().GetField("_timeoutState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(System.Web.HttpContext.Current, 1);
Therefore, changing the TimeoutFilter OnActionExecuting() to:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
System.Web.HttpContext.Current.GetType().GetField("_timeoutState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(System.Web.HttpContext.Current, 1);
base.OnActionExecuting(filterContext);
}
and setting the web.config:
<configuration>
<system.web>
<compilation debug="false" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5" executionTimeout="5"/>
...
allows the time-out to work but has the slight 5 second delay that is mentioned in the first post.
Note: Using this method does not allow you to set the ScriptTimeout property in the filter. Trying to set ScriptTimeout and override the value set in web.config does not appear to work.
Are you using a debug build?
From the ScriptTimeout documentation:
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.scripttimeout(v=vs.110).aspx
If you set the debug attribute of the compilation element to true in the Web.config file, the value of ScriptTimeout will be ignored.
Also, since this value is the same as that set on the httpRuntime element, I really don't understand the point of this, since you can just configure that setting in in your web.config instead.
Edit:
Dangerous has done a good job of finding out the details, and indeed, ScriptTimeout is unsupported in asynchronous pipelines (which MVC has been since at least MVC4 I think, as well as WebApi.. even if not using async methods)
The "workaround" as suggested by this connect report:
https://connect.microsoft.com/VisualStudio/feedback/details/781171/asp-net-mvc-executiontimeout-does-not-work
Use the [AsyncTimeout] attribute, and take a cancelation token as a parameter, then call CanclationToken.ThrowIfCancelationRequested periodically, or use the cancellation token in an async method.
Here's an example:
[AsyncTimeout(5000)]
public async Task<ContentResult> Index(CancellationToken ct)
{
await Task.Delay(10 * 1000, ct);
return Content("This should never get returned, mwahahaaa!");
}
This throws an OperationCanceled exception with a YSOD after 5 seconds. The bonus for this is that it works even in Debug mode ;)

All ASP.NET Web API controllers return 404

I'm trying to get an API Controller to work inside an ASP.NET MVC 4 web app. However, every request results in a 404 and I'm stumped. :/
I have the standard API controller route from the project template defined like:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
The registration is invoked in Global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// Register API routes
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
I have a basic API controller like this:
namespace Website.Controllers
{
public class FavoritesController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new [] { "first", "second" };
}
// PUT api/<controller>/5
public void Put(int id)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}
Now, when I browse to localhost:59900/api/Favorites I expect the Get method to be invoked, but instead I get a 404 status code and the following response:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:59900/api/Favorites'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'Favorites'.
</MessageDetail>
</Error>
Any help would be greatly appreciated, I'm losing my mind a little bit over here. :) Thanks!
One thing I ran into was having my configurations registered in the wrong order in my GLobal.asax file for instance:
Right Order:
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
Wrong Order:
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
WebApiConfig.Register(GlobalConfiguration.Configuration);
Just saying, this was my problem and changing the order is obvious, but sometimes overlooked and can cause much frustration.
Had essentially the same problem, solved in my case by adding:
<modules runAllManagedModulesForAllRequests="true" />
to the
<system.webServer>
</system.webServer>
section of web.config
I have been working on a problem similar to this and it took me ages to find the problem. It is not the solution for this particular post, but hopefully adding this will save someone some time trying to find the issue when they are searching for why they might be getting a 404 error for their controller.
Basically, I had spelt "Controller" wrong at the end of my class name. Simple as that!
Add following line
GlobalConfiguration.Configure(WebApiConfig.Register);
in Application_Start() function in Global.ascx.cs file.
I had the same problem, then I found out that I had duplicate api controller class names in other project and despite the fact that the "routePrefix" and namespace and project name were different but still they returned 404, I changed the class names and it worked.
Similar problem with an embarrassingly simple solution - make sure your API methods are public. Leaving off any method access modifier will return an HTTP 404 too.
Will return 404:
List<CustomerInvitation> GetInvitations(){
Will execute as expected:
public List<CustomerInvitation> GetInvitations(){
For reasons that aren't clear to me I had declared all of my Methods / Actions as static - apparently if you do this it doesn't work. So just drop the static off
[AllowAnonymous]
[Route()]
public static HttpResponseMessage Get()
{
return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}
Became:-
[AllowAnonymous]
[Route()]
public HttpResponseMessage Get()
{
return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}
Create a Route attribute for your method.
example
[Route("api/Get")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
You can call like these http://localhost/api/Get
Had this problem. Had to uncheck Precompile during publishing.
I'm a bit stumped, not sure if this was due to an HTTP output caching issue.
Anyways, "all of a sudden it started working properly". :/ So, the example above worked without me adding or changing anything.
Guess the code just had to sit and cook overnight... :)
Thanks for helping, guys!
I'm going to add my solution here because I personally hate the ones which edit the web.config without explaining what is going on.
For me it was how the default Handler Mappings are set in IIS. To check this...
Open IIS Manager
Click on the root node of your server (usually the name of the server)
Open "Handler Mappings"
Under Actions in the right pane, click "View ordered list"
This is the order of handlers that process a request. If yours are like mine, the "ExtensionlessUrlHandler-*" handlers are all below the StaticFile handler. Well that isn't going to work because the StaticFile handler has a wildcard of * and will return a 404 before even getting to an extensionless controller.
So rearranging this and moving the "ExtensionlessUrlHandler-*" above the wildcard handlers of TRACE, OPTIONS and StaticFile will then have the Extensionless handler activated first and should allow your controllers, in any website running in the system, to respond correctly.
Note:
This is basically what happens when you remove and add the modules in the web.config but a single place to solve it for everything. And it doesn't require extra code!
Check that if your controller class has the [RoutePrefix("somepath")] attribute, that all controller methods also have a [Route()] attribute set.
I've run into this issue as well and was scratching my head for some time.
WebApiConfig.Register(GlobalConfiguration.Configuration);
Should be first in App_start event. I have tried it at last position in APP_start event, but that did not work.
I found this in a comment here: https://andrewlock.net/when-asp-net-core-cant-find-your-controller-debugging-application-parts/
Add the following to your Program.cs:
app.UseRouting();
app.UseEndpoints(endpoints =>
{
// DP: I don't know the purpose of this, but without it, all controllers report 404
endpoints.MapControllerRoute("default", "WTF is this");
});
For me this is all it took to make it work after hours of trying to find a solution. If this doesnt work for you, try adding
builder.Services.AddControllers();
Add this to <system.webServer> in your web.config:
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
<remove name="OPTIONSVerbHandler"/>
<remove name="TRACEVerbHandler"/>
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0"/>
</handlers>
Adding <modules runAllManagedModulesForAllRequests="true" /> also works but is not recommended due performance issues.
I have solved similar problem by attaching with debugger to application init. Just start webserver (for example, access localhost), attach to w3wp and see, if app initialization finished correctly. In my case there was exception, and controllers was not registered.
I had the same 404 issue and none of the up-voted solutions here worked. In my case I have a sub application with its own web.config and I had a clear tag inside the parent's httpModules web.config section. In IIS all of the parent's web.config settings applies to sub application.
<system.web>
<httpModules>
<clear/>
</httpModules>
</system.web>
The solution is to remove the 'clear' tag and possibly add inheritInChildApplications="false" in the parent's web.config. The inheritInChildApplications is for IIS to not apply the config settings to the sub application.
<location path="." inheritInChildApplications="false">
<system.web>
....
<system.web>
</location>
I have dozens of installations of my app with different clients which all worked fine and then this one just always returned 404 on all api calls. It turns out that when I created the application pool in IIS for this client it defaulted to .net framework 2.0 instead of 4.0 and I missed it. This caused the 404 error. Seems to me this should have been a 500 error. Very misleading Microsoft!
I had this problem: My Web API 2 project on .NET 4.7.2 was working as expected, then I changed the project properties to use a Specific Page path under the Web tab. When I ran it every time since, it was giving me a 404 error - it didn't even hit the controller.
Solution: I found the .vs hidden folder in my parent directory of my VS solution file (sometimes the same directory), and deleted it. When I opened my VS solution once more, cleaned it, and rebuilt it with the Rebuild option, it ran again. There was a problem with the cached files created by Visual Studio. When these were deleted, and the solution was rebuilt, the files were recreated.
If you manage the IIS and you are the one who have to create new site then check the "Application Pool" and be sure the CLR version must be selected. In my situation, it had been selected "No Managed Code". After changed to v4.0 it started to work.
i try above but not sucess all
add ms webhost and GlobalConfiguration.Configure(WebApiConfig.Register);

Why is the HttpContext.Cache count always zero?

I set up a few pages with OutputCache profiles and confirmed that they are being cached by using multiple browsers and requests to retrieve the page with a timestamp which matched across all requests. When I try to enumerate the HttpContect.Cache it is always empty.
Any ideas what is going on here or where I should be going for this information instead?
Update:
It's not client cache because multiple browsers are seeing the same response. Here is a bit of code to explain what's happening.
Web.Config caching settings
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<clear/>
<add name="StaticContent" duration="1200" varyByParam="none"/>
<add name="VaryByParam" duration="1200" varyByParam="*"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
...
</system.web>
**Action Method With Caching
[OutputCache(CacheProfile = "StaticContent")]
public ActionResult Index()
{
return View(new CollaborateModel());
}
Code to enumerate the cache, yep it's rough, an this is defined in a controller action method
var sb = new StringBuilder();
foreach (KeyValuePair<string, object> item in HttpContext.Cache)
{
sb.AppendFormat("{0} : {1}<br />", item.Key, item.Value.ToString());
}
ViewData.Add("CacheContents", sb.ToString());
The HttpContext.Cache is where the count is always null, even though the cache seems to be working fine.
That's probably because the page has been cached downstream on the client browser and not on the server.
Instead of using the HttpCache I ended up rolling my own caching model for holding datasets in my Data Access layer. If I was looking up the AD profile of a given username and converting it to a DTO then I just put that profile in a rolling collection of profile DTOs that I would check before polling AD for the information.

Resources