环境:Windows Server 2012 R2,IIS 8.5。web-api - 适用于开发,而不是在实际的服务器上 - 未解析JSON
我构建了一个在我们的开发环境中创建奇迹的API。它读取文本文件,然后将内容序列化为JSON并返回。我做了一个文件系统部署到我们的服务器。我创建了一个指向该文件夹的网站,并认为它会很好地实现这一诀窍。我将该网站设为默认网站。
我的应用程序中包含的路由处理两个不同的路线:
/api/twitter/{date}
/api/twitter/{date}/{id}
两种路线应该吐出一个JSON字符串。
打开服务器,输入localhost
调出本地主机屏幕。 localhost/api
产生一个404.0 not found
,这听起来没什么问题,因为没有办法处理这个问题。 localhost/api/twitter/20160201
,它应该工作,并没有真正做任何事情。它似乎想要下载名为20160201的文件。单击open
什么也不做,并且单击save
会生成一个永不完成的空文件。我怀疑JSON.NET没有正确地被调用,或者服务器可能以某种方式不期待JSON被返回给Breowser。
在错误消息中,我可以看到物理路径至少指向正确的路径。
这里的控制器部分:
// Default route:
[Route("api/twitter/{date}")]
public Twitter GetTweets(int date) {
return LoadJson(date);
}
// Additional route for date + id for incremental loading
[Route("api/twitter/{date}/{id}")]
[HttpGet]
public Twitter GetTweets(int date, Int64 id) {
return GetTweetsIncremental(date, id);
}
// more code
WebApiConfig
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(新RequestHeaderMapping( “接受”, “text/html的”,StringComparison.InvariantCultureIgnoreCase, true,“application/json”)); //网页API配置和服务
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{date}",
defaults: new { date = RouteParameter.Optional}
);
Global.asax中包含此片段有API吐出JSON而不是XML:
// Remove the XML formatter
// GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
var serializerSettings =
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
var contractResolver =
(DefaultContractResolver)serializerSettings.ContractResolver;
contractResolver.IgnoreSerializableAttribute = true;
它依赖于Newtonsoft.Json,这是我看到的一个引用,以及我在代码中使用的内容。我还将其标记为“Copy Local = true”引用,以确保Publish将DLL推送到服务器。
在我的web.config,我看到下面的组件绑定(注意缺乏Newtonsoft.json的):
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
</assemblyBinding>
我敢此刻难倒到发生了什么。我最初怀疑这是404错误,这让我尝试了不同的事情,但是我得出结论,因为当我访问实际路线时发生了这种情况,所以我一直在咆哮着错误的树。我无法弄清楚发生了什么问题。
它是缺少对牛顿软件组件的参考吗?如果是这样,我怎么去得到正确的登记?
任何想法?
谢谢。
这里没有太多的事情可以做。首先,使用合适的API客户端。至少使用Fiddler来看看。然后,如果发生任何错误,请检查它们。 – CodeCaster