MediaTypeFormatter因不支持的媒体类型而被点击

时间:2019-03-29 15:36:14

标签: c# asp.net-web-api owin

我正在使用Owin / WebAPI。 我定义了一个自定义CSV格式程序,并且仅当指定了预期的请求有效负载并且代码中显式支持资源类型时,才希望使用此格式程序。例如接受:文本/ csv 因此,对于标准的“ application / json”内容,我不希望调用CanWriteType(),因为我有特殊的处理方式,可以在支持请求时返回400 Bad请求。 但是,我可以看到所有请求(包括标准application / json媒体类型)都被调用CanWriteType()。 这是预期的吗? CustomCSVMediaTypeFormatter是否可以将其锁定,以便仅在请求csv格式时调用它?

    public class CustomCSVMediaTypeFormatter : MediaTypeFormatter
        {
            Func<Type, Type> _getUnderlyingDataType = (type) => type.GetGenericArguments().FirstOrDefault()?.GetGenericArguments().FirstOrDefault();
            readonly IEnumerable<Type> _supportedResponsePayloadTypes = new List<Type> { typeof(Foo) };

            public CustomCSVMediaTypeFormatter()
            {
                SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
            }


            public override bool CanWriteType(Type type)
            {
                if (type == typeof(HttpError))
                    return false;
                if(_supportedResponsePayloadTypes.Contains(_getUnderlyingDataType(type)))
                    return true;
              throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotImplemented));
            }
}

0 个答案:

没有答案