我的 WebAPI 控制器发生了一个奇怪的问题。
在我的开发环境(Win7,IIS 7.5)中,控制器上的方法被调用,结果按预期返回。
在我的集成环境(WIN Server 2003,IIS 6.0)中,我通过将代码从我的开发框复制到集成框来部署代码。调用控制器上的方法并返回以下错误:
“没有 MediaTypeFormatter 可用于从媒体类型为“text/html”的内容中读取“EmailQueueResult”类型的对象。”
我不明白为什么我只在我的集成环境中而不是在我的开发环境中得到这个错误。
public HttpResponseMessage Post([FromBody]EmailQueueMessage email)
{
EmailQueueResult result;
if (email != null)
{
try
{
var emailQueueIdList = QueueEmails(email);
QueueAttachments(email, emailQueueIdList);
foreach(var emailQueueId in emailQueueIdList)
{
UpdateEmailQueueDateQueued(emailQueueId, DateTime.Now);
}
result = new EmailQueueResult(0, "Email added to queue.", "", null);
}
catch (Exception e) {
result = new EmailQueueResult(2, "Error occurred.", e.Message, null);
}
}
else
{
result = new EmailQueueResult(1, "Email passed in was null.", "", null);
}
return ControllerContext.Request.CreateResponse(HttpStatusCode.OK, result, "application/json");
}
WebApiConfig.cs:
namespace App_Start
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
"ControllerWithBooleanParameter",
"api/{controller}/{showSentEmails}",
null,
new { boolConstraint = new IsBoolean() }
);
config.Routes.MapHttpRoute(
"ControllerWithIntegerParameter",
"api/{controller}/{id}",
null,
new { id = @"^\d+$" }
);
config.Routes.MapHttpRoute(
"Default",
"api/{controller}/{id}",
new { id = UrlParameter.Optional }
);
}
}
}
网络配置:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
<mailSettings>
<smtp from="address@email.com">
<network host="smtp.server.com" port="25" />
</smtp>
</mailSettings>
</system.net>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="None" />
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
我也试过让这个方法只返回一个直接的 EmailQueueResult,这给了我相同的结果。
编辑:这是我尝试的更多测试以及他们的结果:
- 当我使用外部工具向本地计算机上的 Web 服务发送 POST 请求时,它按预期工作。
- 当我使用我的本地代码副本执行调用 Web 服务的代码时,它按预期工作。
- 当我使用外部工具向集成机器上的 Web 服务发送 POST 请求时,它按预期工作。
- 当我使用集成机器执行调用 Web 服务的代码时,出现上述错误。
发送 POST 的代码行:
EmailQueueResult result = PostToWebService<EmailQueueMessage, EmailQueueResult>(EmailQueueBaseAddress, "application/json", EmailQueueUrlToCall, emailQueueMessage);
实际进行调用的 PostToWebService 方法:
protected returnType PostToWebService<dataType, returnType>(string baseAddress, string mediaType, string urlToCall, dataType data)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(mediaType));
MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
HttpContent content = new ObjectContent<dataType>(data, jsonFormatter);
HttpResponseMessage response = client.PostAsync(urlToCall, content).Result;
returnType result = response.Content.ReadAsAsync<returnType>().Result;
return result;
}
更新:我在 2008 服务器上安装了网站和 Web 服务。唯一失败的组合似乎是从 2003 盒子上的网站调用 2003 盒子上的 Web 服务(2003 站点 -> 2003 服务)。其他三个组合(2008 站点 -> 2008 服务、2008 站点 -> 2003 服务、2003 站点 -> 2008 服务)似乎都工作正常。