asp.net mvc keeps overriding text/html content-typ

2019-02-11 08:57发布

问题:

I'm developing an website which is to be viewed on mobile (cellphone) devices. I'm just using plain HTML 4.01, nothing special at all. The pages render fine on all the mobile browsers we've tested, except for Nokia Series 40 1-5th editions. On closer inspection, it seems that IIS is automatically rendering the html with the content-type of text/vnd.wap.wml instead of text/html. Since we're not using WAP, the page fails with an error.

I'm using ASP.Net MVC 1.0 so I've added a ActionFilterAttribute to override the content-type. This code runs but still comes out as vnd.wap.wml on the client side.
I'm using this doctype;

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

It's worth noting that the vnd.wap.wml is the first Accept-Encoding specified by the mobile browser, so I assume IIS7 is serving it up for that reason. And I guess as MVC doesn't specifically refer to .html (or .aspx) files, maybe the mime-type is being skipped? I suspect this is probably an IIS fix rather than a code-fix.

Any help is much appreciated!

回答1:

Turns out I hadn't implemented the ActionFilter correctly.. I needed to override the OnResultExecuted method in addition to the OnActionExecuted method. The full attribute looks like this (just add [HtmlOverrideFilter] to your Controllers where needed). Hope this helps someone.

internal class HtmlOverrideFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.ContentType = "text/html";
    } 

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.ContentType = "text/html";
    }
}