MissingMethodException Global.asax.cs - PullRequest
0 голосов
/ 26 ноября 2018

Из-за этого сообщения в блоге:

https://www.radenkozec.com/8-ways-improve-asp-net-web-api-performance/

Я пытался заменить JSON.net на ServiceStack.Text в качестве JSON-Serializer в моем WebApi.С этим руководством:

https://www.strathweb.com/2013/01/replace-json-net-with-servicestack-text-in-asp-net-web-api/

На локальном хосте и в режиме отладки все прошло хорошо, пока я не развернул его на нашем сервере, он говорит:

MissingMethodException

[MissingMethodException: метод не найден: "System.Collections.ObjectModel.CollectionSystem.Web.Http.HttpConfiguration.get_MessageHandlers () ".]

Это происходит в Application_Start ().

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);

}

Вот моя замена:

public class ServiceStackTextFormatter : JsonMediaTypeFormatter
{
    public ServiceStackTextFormatter()
    {
        JsConfig.DateHandler = DateHandler.ISO8601;
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

        SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
        SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));
    }

    public override bool CanReadType(Type type)
    {
        if (type == null) throw new ArgumentNullException("type");
        return true;
    }

    public override bool CanWriteType(Type type)
    {
        if (type == null) throw new ArgumentNullException("type");
        return true;
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
    {
        var task = Task<object>.Factory.StartNew(() => JsonSerializer.DeserializeFromStream(type, readStream));
        return task;
    }

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
    {
        var task = Task.Factory.StartNew(() => JsonSerializer.SerializeToStream(value, type, writeStream));
        return task;
    }
}

И мой метод регистрации:

public static void Register(HttpConfiguration config)
    {
        // see this: https://www.strathweb.com/2013/01/replace-json-net-with-servicestack-text-in-asp-net-web-api/
        // and this: https://www.radenkozec.com/8-ways-improve-asp-net-web-api-performance/
        // ServiceStackText is much faster than JSON.NET
        config.Formatters.RemoveAt(0);
        config.Formatters.Insert(0, new ServiceStackTextFormatter());

        // add Handler to send data chunked
        config.MessageHandlers.Add(new Handler());

        // Web API configuration and services
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.EnableCors();      // needed to disable this, otherwise we do not get a access-origin-header in the client

        config.Formatters[0].SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
        config.Formatters[0].SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
        config.Formatters[0].SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        (config.Formatters[0] as ServiceStackTextFormatter).SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;
    }

1 Ответ

0 голосов
/ 27 ноября 2018

Так что я добился определенного прогресса.Проблема не была вызвана ServiceStack-JSON-Serializer, она вызвана моим обработчиком:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace akiliBase.Rest.RestAPI.Models
{
    public class Handler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            var response = base.SendAsync(request, cancellationToken);

            response.Result.Headers.TransferEncodingChunked = true; // Here!

            return response;
        }
    }
}

Поэтому я удалил эту строку и задам еще один вопрос по этому поводу.Теперь я получаю следующую ошибку:

[MissingMethodException: метод не найден: "System.Collections.ObjectModel.Collection`1 System.Net.Http.Formatting.MediaTypeFormatter.get_SupportedMediaTypes ()".]

, что вызвано следующими строками:

config.Formatters[0].SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
config.Formatters[0].SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
config.Formatters[0].SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

Таким образом, в System.Net.Http.Formatting.MediaTypeFormatter он получит геттер для SupportedMediaTypes.Я также думаю, что вся проблема вызвана в Web.config, где ссылаются на некоторые неправильные ассамбли или что-то в этом роде.Итак, вот мой web.config-runtime-tag:

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Build.Framework" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-15.1.0.0" newVersion="15.1.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System" publicKeyToken="b77a5c561934e089" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Cors" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.2.6.0" newVersion="5.2.6.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="ZedGraph" publicKeyToken="02a83cbd123fcd60" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.1.7.430" newVersion="5.1.7.430" />
  </dependentAssembly>
</assemblyBinding>

...