相关疑难解决方法(0)

无法在Web API中序列化响应

我正在使用ASP.NET MVC Web API,我遇到了这个错误:

'ObjectContent`1'类型无法序列化内容类型'application/xml的响应主体; 字符集= UTF-8' .

我的控制器是:

public Employee GetEmployees()
{
    Employee employees = db.Employees.First();
    return employees;
}
Run Code Online (Sandbox Code Playgroud)

为什么我收到这个错误?

c# serialization asp.net-web-api

84
推荐指数
7
解决办法
9万
查看次数

如何从存储过程返回XML?

我创建了一个返回XML的存储过程,我想在我创建的方法中返回该XML.

我有两个问题.首先,在进行一些搜索之后,建议不要使用.ExecuteScalar();它,因为它会截断超过2033个字符的字符串.

所以,我发现了一个名为的函数ExecuteXMlReader(),但是在.NET 4.0(C#)上运行的Visual Web Developer 2010 Express中,它抛出了错误 "System.Data.SqlClient.SqlCommand' does not contain a definition for 'ExecuteXMlReader' and no extension method 'ExecuteXMlReader' accepting a first argument of type 'System.Data.SqlClient.SqlCommand' could be found"

这是我的存储过程:

CREATE PROCEDURE dbo.GETReport
    (@ReportDate date)
AS
SELECT * FROM ReportTbl
WHERE ReportDate = @ReportDate
for xml auto, elements

set nocount on;

RETURN
Run Code Online (Sandbox Code Playgroud)

这是我的方法:

using System.Data;
using System.Data.SqlClient;

...

        //connect        
        SqlConnection conn = new SqlConnection("Data Source=localhost; User Id=foo; Password=foo; Initial Catalog=Database1");
        conn.Open();

        //create command
        SqlCommand …
Run Code Online (Sandbox Code Playgroud)

.net c# xml stored-procedures

20
推荐指数
2
解决办法
3万
查看次数

如何从Web API方法返回Xml数据?

我有一个Web Api方法,它应返回一个xml数据,但它返回字符串:

 public class HealthCheckController : ApiController
    {       
        [HttpGet]
        public string Index()
        {
            var healthCheckReport = new HealthCheckReport();

            return healthCheckReport.ToXml();
        }
    }
Run Code Online (Sandbox Code Playgroud)

它返回:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
<myroot><mynode></mynode></myroot>
</string>
Run Code Online (Sandbox Code Playgroud)

我添加了这个映射:

 config.Routes.MapHttpRoute(
              name: "HealthCheck",
              routeTemplate: "healthcheck",
              defaults: new
              {
                  controller = "HealthCheck",
                  action = "Index"
              });
Run Code Online (Sandbox Code Playgroud)

如何使它只返回xml位:

<myroot><mynode></mynode></myroot>
Run Code Online (Sandbox Code Playgroud)

如果我只使用MVC,我可以使用下面的内容,但Web API不支持"内容":

 [HttpGet]
        public ActionResult Index()
        {
            var healthCheckReport = new HealthCheckReport();

            return Content(healthCheckReport.ToXml(), "text/xml");
        }
Run Code Online (Sandbox Code Playgroud)

我还在WebApiConfig类中添加了以下代码:

 config.Formatters.Remove(config.Formatters.JsonFormatter);
 config.Formatters.XmlFormatter.UseXmlSerializer = true;
Run Code Online (Sandbox Code Playgroud)

xml asp.net-mvc asp.net-web-api

20
推荐指数
1
解决办法
3万
查看次数