如何更改ASP.NET MVC控制器中返回的ContentType(ActionResult)

jma*_*mav 21 asp.net asp.net-mvc asp.net-ajax asp.net-mvc-2

我有ASP.NET MVC控制器命名字典与方法ControlsLangJsFile.方法返回包含JavaScript变量的用户控件(ASCX)视图.

当我调用该方法时,它返回带有解析字符串的变量,但内容类型是html/text.它应该是:application/x-javascript

public ActionResult ControlsLangJsFile()
    {
        return View("~/Views/Dictionary/ControlsLangJsFile.ascx",);
    }
Run Code Online (Sandbox Code Playgroud)

我如何实现这一目标?

jma*_*mav 35

用户控件不接受ContentType ="text/xml"

解:

public ActionResult ControlsLangJsFile()
    {
        Response.ContentType = "text/javascript";
        return View("~/Views/Dictionary/ControlsLangJsFile.ascx");
    }
Run Code Online (Sandbox Code Playgroud)

  • 这不适用于Razor视图(不确定其他视图引擎).有关解决方案,请参阅[我的回答](http://stackoverflow.com/a/15930411/5496): (2认同)

Pet*_*ter 17

我在使用JS构建剃刀视图时尝试使用@jmav的解决方案时遇到了同样的问题:

public ActionResult Paths()
{
    Response.ContentType = "text/javascript"; //this has no effect
    return View();
}
Run Code Online (Sandbox Code Playgroud)

当您返回View()时,这不起作用.尽管在控制器方法中分配了内容,但视图呈现似乎设置了内容类型本身.

相反,在视图代码中进行赋值:

// this lives in viewname.cshtml/vbhtml
@{
    this.Response.ContentType = "text/javascript";
}
// script stuff...
Run Code Online (Sandbox Code Playgroud)

  • 在MVC 3中,在Controller动作中设置`Response.ContentType`对我有用。 (2认同)