我是 Web API 的新手。我正在为我的团队进行概念验证项目,我们将在其中创建基于 Web-API XML 数据源的 SSRS 2012 报告。但是,不应将 Web-API 配置为仅将 XML 作为内容类型进行协商。在未来的阶段,我们的网络应用程序应该能够从相同的 Controller /操作中检索 json 对象。
我开始关注 this tutorial一切正常,没问题。
接下来我配置了我的路由以便我可以直接调用操作,我将 QueryStringMappings 添加到我的 Global.asax 以便我可以指定内容类型。
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
}
}
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
GlobalConfiguration.Configuration.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");
}
}
效果很好,我现在可以使用 localhost:XXXXX/api/Products/GetAllProducts/?$format=xml 作为我在 SSRS 中的数据源连接字符串。我不确定这是否是最好的方法,但它奏效了,所以我坚持了下来。如果没有查询字符串映射,数据源将无法在 SSRS 中工作。
这是我遇到麻烦的地方。我分支并创建了我的第一个模型/ Controller / Action 。当我在浏览器(chrome 或 IE 10)中运行该项目并尝试将格式指定为 XML (localhost:XXXXX/api/Calcs/ComputeFooCalculation?$format=xml) 时,我得到了一个 json 结果。 Products Controller 继续适用于 json 或 xml 内容类型。但出于某种原因,我的操作只会呈现为 json。这是我的代码的样子。如果您需要模型或其他任何东西,请告诉我。 FooCalculation 有一个嵌套对象 Bar。 FooCalculation 和 Bar 都有字符串、 double 和日期时间。
Controller :
public class CalcsController : ApiController
{
public FooCalculation ComputeFooCalculation()
{
var Foo = GetFoo();
var Bar = GetBar();
var FooCalculation = new FooCalculation(Foo, Bar);
return FooCalculation;
}
}
示例 JSON 结果:
{"Foo":"XXX","FooRate":{"Foo":"XXX","Bar":"SN","FooBar":-1.00813E-05,"BarFoo":-3.2644199999999995E-06,"FoooBarrr":-4.17501E-06,"BarDate":"2013-05-14T00:00:00"},"BarRate":{"Foo":"XXX","Bar":"1W","FooBar":-2.08687E-05,"BarFoo":-3.11313E-05,"FoooBarrr":-3.3E-05,"BarDate":"2013-05-21T00:00:00"},"BarDate":"2013-05-20T00:00:00","FooDays":6,"FooBar":-7.3741306716417904E-06,"Bar":-0.0011149741306716415}
在此先感谢您的帮助。
最佳答案
在您的模型类中放置一个无参数构造函数。 XML 格式试图在您检索所有数据之前实例化一个空的 XML 树。
关于xml - Web API 返回 JSON 内容类型而不是 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16451674/