WebApi 将ModelBinder ValueProvider 加入到项目中

設定模型系結器

有幾種方式可以設定模型系結器。 首先,您可以將 [ModelBinder] 屬性加入至參數。

public HttpResponseMessage Get([ModelBinder(typeof(GeoPointModelBinder))] GeoPoint location)

您也可以將 [ModelBinder] 屬性加入至類型。 Web API 會針對該類型的所有參數使用指定的模型系結器。

[ModelBinder(typeof(GeoPointModelBinder))]
public class GeoPoint
{
    // ....
}

最後,您可以將模型系結器提供者加入至 HttpConfiguration。 模型系結器提供者只是建立模型系結器的 factory 類別。 您可以藉由衍生自 ModelBinderProvider 類別來建立提供者。 但是,如果您的模型系結器會處理單一型別,則使用內建的 SimpleModelBinderProvider 會更容易使用,這是專為此用途所設計。 下列程式碼示範如何執行這項操作。

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var provider = new SimpleModelBinderProvider(
            typeof(GeoPoint), new GeoPointModelBinder());
        config.Services.Insert(typeof(ModelBinderProvider), 0, provider);

        // ...
    }
}

使用模型系結提供者時,您仍然必須將 [ModelBinder] 屬性加入至參數,以告知 Web API 應該使用模型系結器,而不是媒體類型格式器。 但現在您不需要在屬性中指定模型系結器的類型:

public HttpResponseMessage Get([ModelBinder] GeoPoint location) { ... }



ValueProvider

public class CookieValueProviderFactory : ValueProviderFactory
{
    public override IValueProvider GetValueProvider(HttpActionContext actionContext)
    {
        return new CookieValueProvider(actionContext);
    }
}

將值提供者 factory 新增至 HttpConfiguration ,如下所示。

public static void Register(HttpConfiguration config)
{
    config.Services.Add(typeof(ValueProviderFactory), new CookieValueProviderFactory());

    // ...
}

Web API 會撰寫所有值提供者,因此當模型系結器呼叫 ValueProvider 時,模型系結器會接收第一個可產生它的值提供者的值。

或者,您可以使用 ValueProvider 屬性,在參數層級設定值提供者 factory,如下所示:

public HttpResponseMessage Get(
    [ValueProvider(typeof(CookieValueProviderFactory))] GeoPoint location)


posted @ 2021-11-03 17:21  zq爱生活爱代码  阅读(36)  评论(0编辑  收藏  举报