Webapi自定义JsonMediaTypeFormatter

时间:2014-12-22 09:59:04

标签: json asp.net-web-api

我正在尝试创建一个自定义的JSONMediaTypeFormatter,其中将一些json参数发布到webapi调用。我需要加密来自webapi的返回数据,因此编写自定义mediatype格式。

在我的webapiconfig中,我清除所有格式化程序,只添加自定义格式化程序。

        config.Formatters.Clear();
        config.Formatters.Add(new CipherMediaFormatter());

在我的自定义媒体类型格式化程序中,我添加了相关的标题和类型,但我仍然无法调用我的web api。它给了我一个错误

     No MediaTypeFormatter is available to read an object of type 'Param' from content with media type        'application/json

mediatypeformatter的代码

public class CipherMediaFormatter : JsonMediaTypeFormatter
{
    private static Type _supportedType = typeof(object);

    public CipherMediaFormatter()
    {
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/octet-stream"));
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
    }

    public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
    {
        base.SetDefaultContentHeaders(type, headers, mediaType);
        headers.ContentType = new MediaTypeHeaderValue("application/json");
    }

    public override bool CanReadType(Type type)
    {
        return true;
    }

    public override bool CanWriteType(Type type)
    {
        return true;
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        var taskSource = new TaskCompletionSource<object>();
        try
        {
            var ms = new MemoryStream();
            readStream.CopyTo(ms);
            taskSource.SetResult(ms.ToArray());
        }
        catch (Exception e)
        {
            taskSource.SetException(e);
        }
        return taskSource.Task;
    }

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
    {
        var taskSource = new TaskCompletionSource<object>();
        try
        {
            if (value != null)
            {
                var jsonData = JsonConvert.SerializeObject(value);
                ICryptographicService cgService = new CryptographicService();
                string apiKey = string.Empty;

                string pattern = @"api\/(.*)?\/(\d+)?";
                var match = Regex.Match(HttpContext.Current.Request.RawUrl, pattern);
               ....
            }
        }
        catch (Exception e)
        {
            taskSource.SetException(e);
        }
        return taskSource.Task;
    }
}

1 个答案:

答案 0 :(得分:0)

问题是ReadFromStreamAsync导致mediatypeformatter错误。