为什么WebAPI会引发“无MediaTypeFormatter"错误? [英] Why is WebAPI Throwing a 'No MediaTypeFormatter' Error?

查看:98
本文介绍了为什么WebAPI会引发“无MediaTypeFormatter"错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的WebAPI控制器发生了一个奇怪的问题.

I have a strange issue happening with my WebAPI controller.

在我的开发环境(Win7,IIS 7.5)中,调用了控制器上的方法,并按预期返回了结果.

In my development environment (Win7, IIS 7.5) the method on the controller is called and the result is returned as expected.

在集成环境(WIn Server 2003,IIS 6.0)中,我已经通过将代码从开发箱复制到集成箱来部署了代码.调用控制器上的方法,并返回以下错误:

In my integration environment (WIn Server 2003, IIS 6.0) I have deployed the code by copying it from my development box to the integration box. The method on the controller is called and returns the following error:

没有MediaTypeFormatter可用于读取类型为" EmailQueueResult的对象内容类型为"text/html"的内容."

"No MediaTypeFormatter is available to read an object of type "EmailQueueResult" from content with media type "text/html"."

我不明白的是为什么我只在集成环境中而不是在开发环境中出现此错误.

What I don't understand is why I only get this error in my integration environment and not in my development environment.

    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:

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:

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="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,这给了我相同的结果.

I have also tried having this method just return a straight EmailQueueResult, and that gave me the same results.

这里还有一些我尝试过的测试以及它们的结果:

Here are some more tests that I tried along with their results:

  • 当我使用外部工具将POST请求发送到本地计算机上的Web服务时,它会按预期工作.
  • 当我执行使用本地代码副本调用Web服务的代码时,它会按预期工作.
  • 当我使用外部工具将POST请求发送到集成计算机上的Web服务时,它会按预期工作.
  • 当我执行使用集成机调用Web服务的代码时,出现上述错误.

发送POST的代码行:

The line of code that sends the POST:

        EmailQueueResult result = PostToWebService<EmailQueueMessage, EmailQueueResult>(EmailQueueBaseAddress, "application/json", EmailQueueUrlToCall, emailQueueMessage);

实际进行调用的PostToWebService方法:

The PostToWebService method that actually makes the call:

    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服务)似乎都可以正常工作.

UPDATE: I installed the website and web service on a 2008 server. The only combination that fails seems to be when the web service on the 2003 box is called from the website on the 2003 box (2003 site -> 2003 service). The other three combinations (2008 site - > 2008 service, 2008 site -> 2003 service, 2003 site -> 2008 service) all seem to be working correctly.

推荐答案

好吧,事实证明,这与代码无关,正如您中的某些人所表示的那样.基本上,我必须将2003框上的hosts文件中的本地回送地址(127.0.0.1)更改为2003框的实际IP,并且一切都按现在的方式进行.走吧.

Ok, it turns out this had NOTHING to do with the code, as some of you have expressed above. Basically, I had to change the local loopback address (127.0.0.1) in my hosts file on the 2003 box to the actual IP of the 2003 box and everything works as expexted now. Go figure.

这篇关于为什么WebAPI会引发“无MediaTypeFormatter"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆