我怎样才能使这个c#方法通用?

时间:2018-05-03 21:54:11

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

我有下面的类用于验证用户是否使用无效属性提交API请求。我想把这个类变成通用的。例如,我想将此类通用于任何类型的请求对象。例如,UserSearchRequest,GroupSearchRequest,XSearchRequest等。

我最初明确地将DeserializeObject的类型设置为UserSearchRequest,它按预期工作,但现在我正在尝试对此实现进行泛化。我尝试为BindModel()签名提供T,但是为了支持IModelBinder接口,需要当前签名。

我目前的想法是有一个类构造函数,它接受一个Type参数,然后将其设置为一个成员变量,然后在BindModel方法中引用该变量。但我无法让这个工作。我在这里做错了什么?

using System;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using Models.Requests;
using Newtonsoft.Json;

namespace MyCorp.Api
{
    public class CustomModelBinder : IModelBinder
    {
        Type _bindModelType;

        public CustomModelBinder(Type bindModelType)
        {
            _bindModelType = bindModelType;
        }

        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var settings = new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Error
            };

            try
            {
                bindingContext.Model =
                    JsonConvert.DeserializeObject<_bindModelType.GetType()>(
                    actionContext.Request.Content.ReadAsStringAsync().Result,
                    settings);
            }
            catch (Exception ex)
            {
                var split = ex.Message.Split("'".ToCharArray());
                var message = "{0}.{1} is not a valid property";
                var formattedMessage = string.Format(message, split[3], split[1]);
                bindingContext.ModelState.AddModelError("extraProperty", formattedMessage);
            }
            return true;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在移动设备上创作,可能无法编译,但应指向正确的方向。

using System;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using Models.Requests;
using Newtonsoft.Json;

namespace MyCorp.Api
{
    public class CustomModelBinder<T> : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var settings = new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Error
            };

            try
            {
                bindingContext.Model =
                    JsonConvert.DeserializeObject<T>(
                    actionContext.Request.Content.ReadAsStringAsync().Result,
                    settings);
            }
            catch (Exception ex)
            {
                var split = ex.Message.Split("'".ToCharArray());
                var message = "{0}.{1} is not a valid property";
                var formattedMessage = string.Format(message, split[3], split[1]);
                bindingContext.ModelState.AddModelError("extraProperty", formattedMessage);
            }
            return true;
        }
    }
}