ASP.NET MVC 和 text/xml 内容类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/971806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:33:44  来源:igfitidea点击:

ASP.NET MVC and text/xml content type

asp.net-mvcxml

提问by andreialecu

I want to return a View() from an action, and the resulting response should have a content type of text/xml instead of the default text/html.

我想从一个动作返回一个 View(),结果响应的内容类型应该是 text/xml 而不是默认的 text/html。

I have tried the following, with no success:

我尝试了以下方法,但没有成功:

Response.ContentType = "text/xml"; 
return View();

I know that you can specify the content type by returning ContentResult, but that doesn't render my View.

我知道您可以通过返回指定内容类型ContentResult,但这不会呈现我的视图。

I'm hoping I don't need to render the view to a string then use return Content(), so I'm probably overlooking some easy way.

我希望我不需要将视图呈现为字符串然后使用return Content(),所以我可能忽略了一些简单的方法。

回答by eu-ge-ne

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" 
    ContentType="text/xml" %>

回答by Alex

You need to render the string. To return text/xml do the following:

您需要呈现字符串。要返回 text/xml,请执行以下操作:

return new ContentResult {
    ContentType = "text/xml",
    Content = UTF8.GetString(yourXmlString),
    ContentEncoding = System.Text.Encoding.UTF8
}; 

回答by jmav

Users control (ASCX) doesn't accept ContentType="text/xml".

用户控件 (ASCX) 不接受 ContentType="text/xml"。

Solution:

解决方案:

public ActionResult xxx()
  {
     Response.ContentType = "text/xml";
     return View("xxx.ascx");
  }

回答by Alex

If you're looking for Razor (.cshtml) view then set content type in the view code:

如果您正在寻找 Razor (.cshtml) 视图,请在视图代码中设置内容类型:

@{
    Response.ContentType = "text/xml";
}

回答by Richard

You need a view that doesn't override things and generate HTML, including its own context-type.

您需要一个不会覆盖事物并生成 HTML 的视图,包括它自己的上下文类型。

A custom view can directly render to Response.Write (see JsonResultin Reflector for a class that is very similar to what you would need).

自定义视图可以直接呈现到 Response.Write(请参阅JsonResultReflector 中的类,该类与您需要的非常相似)。

To render XML without a intermediate string, save your XML to an XmlWritercreated over Response.Output.

要在没有中间字符串的情况下呈现 XML,请将您的 XML 保存到已XmlWriter创建的Response.Output.

回答by Joel Martinez

Have you tried setting the response.content from the view's pre render method in the codebehind page? that's obviously assuming you're using the webform view engine

您是否尝试在代码隐藏页面中从视图的预渲染方法设置 response.content?这显然是假设您正在使用 webform 视图引擎