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 中工作。
这里是我遇到麻烦的地方。我分支出去创建了我的第一个模型/控制器/操作。当我在浏览器中运行项目(chrome 或 IE 10)并尝试将格式指定为 XML(localhost:XXXXX/api/Calcs/ComputeFooCalculation?$format=xml),我得到了一个 json 结果。 Products 控制器继续对 json 或 xml 内容类型正常工作。但由于某种原因,我的操作只能呈现为 json。这是我的代码样子。如果您需要模型或其他任何东西,请告诉我。FooCalculation 具有嵌套对象 Bar。FooCalculation 和 Bar 都有字符串、双精度和 DateTime。
控制器:
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}
感谢您提前的帮助。