WebAPI 컨트롤러에 이상한 문제가 있습니다.WebAPI가 'No MediaTypeFormatter'오류를 던지는 이유는 무엇입니까?
내 개발 환경 (Win7, IIS 7.5)에서 컨트롤러의 메서드가 호출되고 결과가 예상대로 반환됩니다.
내 통합 환경 (WIn Server 2003, IIS 6.0)에서 개발 상자에서 통합 상자로 코드를 복사하여 배포했습니다. 컨트롤러의 방법이라는 다음과 같은 오류를 반환 : 난 단지 내 개발 환경 내 통합 환경에서이 오류가 발생하지 왜
"No MediaTypeFormatter is available to read an object of type "EmailQueueResult" from content with media type "text/html"."
는 내가 이해하지 못하는 것은.
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 }
);
}
}
}
의 Web.config :
<?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="[email protected]">
<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을 반환 가진 시도, 그리고 나에게 동일한 결과를했다.
편집 : 여기에 내가 그들의 결과와 함께 노력 좀 더 테스트입니다
- 내가 예상대로 작동 외부 도구를 사용하여 내 로컬 컴퓨터의 웹 서비스에 POST 요청을 보낼.
- 로컬 코드 복사본을 사용하여 웹 서비스를 호출하는 코드를 실행하면 예상대로 작동합니다.
- 외부 도구를 사용하여 통합 시스템의 웹 서비스에 POST 요청을 보내면 예상대로 작동합니다.
- 통합 시스템을 사용하여 웹 서비스를 호출하는 코드를 실행할 때 위의 오류가 발생합니다.
에서 POST 전송 코드의 라인 :
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;
}
UPDATE : I가 웹 사이트 및 웹 서비스를 설치 실제로 호출을
EmailQueueResult result = PostToWebService<EmailQueueMessage, EmailQueueResult>(EmailQueueBaseAddress, "application/json", EmailQueueUrlToCall, emailQueueMessage);
PostToWebService 방법 2008 서버. 2003 상자의 웹 사이트 (2003 사이트 -> 2003 서비스)에서 2003 상자의 웹 서비스가 호출 될 때 실패하는 유일한 조합입니다. 다른 세 가지 조합 (2008 사이트 -> 2008 서비스, 2008 사이트 -> 2003 서비스, 2003 사이트 -> 2008 서비스)이 모두 제대로 작동하는 것 같습니다.
콘텐츠 유형을 'application/json; charset = utf-8 ',? 정확한 문제를 파악하기 위해 피 들러를 사용하십시오. – Rifaj
설정을 표시 할 수 있습니까? 그 오류는 그 코드와 전혀 관련이없는 것으로 보입니다. MessageHandlers 또는 전역 작업 필터가 설치되어 있습니까?또한 웹 API _ 적 킷을 설치하여 자세한 정보를 얻을 수도 있습니다. –
@Rifaj - 응답의 컨텐츠 유형이 "application/json"으로 설정됩니다. "charset = utf8"부분을 추가하여 도움이되는지 확인할 수 있습니다. – nikeaa