我的大部分api路由都是这样分割的:
/api/{segment}/MyEntity (即"/api/SegmentA/MyEntity")
其中,我定义了一个ModelBinder,它将字符串转换为Segment对象,如下所示:
class SegmentModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null || String.IsNullOrEmpty(value.AttemptedValue))
return false;
bindingContext.Model = **logic to find segment object from value.AttemptedValue**;
return true;
}
}配置为:
GlobalConfiguration.Configuration.BindParameter(typeof(Segment), new SegmentModelBinder());所以我的路线看起来是这样的:
public class MyEntityController : BaseController
{
[HttpGet, Route("api/{segment}/MyEntity")]
public IEnumerable<MyEntity> Get(Segment segment)
{
...
}
}问题是,我现在正试图为这些Api调用生成文档,而ApiExplorer被这些路由完全搞混了,并忽略了它们。
我如何告诉它,对于这些路由,当它看到Segment类型的参数时,它实际上只是来自路由的一个字符串?
发布于 2015-06-05 16:58:16
从使用ModelBinder切换到TypeConverter解决了这个问题:
[TypeConverter(typeof(MyEntityConverter))]
public class MyEntity
{....-
public class MyEntityConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
var key = value as string;
if (!String.IsNullOrEmpty(key))
return **Find Entity**;
return base.ConvertFrom(context, culture, value);
}
}编辑:
如果您曾经在调用中返回该实体,您也需要在其中使用该实体,否则newtonsoft json序列化程序将将该类序列化为类型名称:
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return false;
}https://stackoverflow.com/questions/30671422
复制相似问题