【问题标题】:How to change returned ContentType in ASP.NET MVC controller (ActionResult)如何在 ASP.NET MVC 控制器中更改返回的 ContentType (ActionResult)
【发布时间】:2011-05-25 06:31:58
【问题描述】:

我有一个名为字典的 ASP.NET MVC 控制器,方法是 ControlsLangJsFile。 方法返回包含 JavaScript 变量的用户控件 (ASCX) 视图。

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

public ActionResult ControlsLangJsFile()
    {
        return View("~/Views/Dictionary/ControlsLangJsFile.ascx",);
    }

我如何做到这一点?

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-2 asp.net-ajax


    【解决方案1】:

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

    解决方案:

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

    【讨论】:

    • 这不适用于 Razor 视图(不确定其他视图引擎)。解决方案见my answer
    • 我正在使用 Razor / MVC 4,这在控制器中工作正常(这是我宁愿放置它的地方,因为如果我返回文件类型,我什至不想要视图,例如 PDF)。
    【解决方案2】:

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

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

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

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

    // this lives in viewname.cshtml/vbhtml
    @{
        this.Response.ContentType = "text/javascript";
    }
    // script stuff...
    

    【讨论】:

    • 在 Controller 操作中设置 Response.ContentType 在 MVC 3 中对我有用。
    【解决方案3】:

    像这样,只需相应地更改内容类型即可:

    ASP.NET MVC and text/xml content type

    【讨论】:

      【解决方案4】:

      试试:

      return Json(new
      {
            uCode = SysContext.CurrentUserCode,
            uPwd = SysContext.CurrentUserPwd,
            rMe = SysContext.RememberMe
      }, "application/json", JsonRequestBehavior.AllowGet);
      

      【讨论】:

        猜你喜欢
        • 2010-11-04
        • 1970-01-01
        • 2017-07-11
        • 1970-01-01
        • 2017-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-11
        相关资源
        最近更新 更多