首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WebApi: ApiExplorer和自定义ModelBinders

WebApi: ApiExplorer和自定义ModelBinders
EN

Stack Overflow用户
提问于 2015-06-05 16:28:01
回答 1查看 328关注 0票数 1

我的大部分api路由都是这样分割的:

/api/{segment}/MyEntity (即"/api/SegmentA/MyEntity")

其中,我定义了一个ModelBinder,它将字符串转换为Segment对象,如下所示:

代码语言:javascript
复制
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;
    }
}

配置为:

代码语言:javascript
复制
GlobalConfiguration.Configuration.BindParameter(typeof(Segment), new SegmentModelBinder());

所以我的路线看起来是这样的:

代码语言:javascript
复制
public class MyEntityController : BaseController
{
    [HttpGet, Route("api/{segment}/MyEntity")]
    public IEnumerable<MyEntity> Get(Segment segment)
    {
        ...
    }
}

问题是,我现在正试图为这些Api调用生成文档,而ApiExplorer被这些路由完全搞混了,并忽略了它们。

我如何告诉它,对于这些路由,当它看到Segment类型的参数时,它实际上只是来自路由的一个字符串?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-05 16:58:16

从使用ModelBinder切换到TypeConverter解决了这个问题:

代码语言:javascript
复制
[TypeConverter(typeof(MyEntityConverter))]
public class MyEntity
{....

-

代码语言:javascript
复制
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序列化程序将将该类序列化为类型名称:

代码语言:javascript
复制
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return false;
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30671422

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档