Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使这种c#方法通用?_C#_Asp.net_Generics_Asp.net Web Api - Fatal编程技术网

如何使这种c#方法通用?

如何使这种c#方法通用?,c#,asp.net,generics,asp.net-web-api,C#,Asp.net,Generics,Asp.net Web Api,下面有一个类,用于验证用户是否提交了带有无效属性的API请求。我想让这个类成为通用类。例如,我想对任何类型的请求对象通用地使用这个类。例如,UserSearchRequest、GroupSearchRequest、XSearchRequest等 我最初将DeserializeObject的类型显式设置为UserSearchRequest,其工作方式与预期一致,但现在我正在尝试将此实现泛化。我尝试为BindModel()签名提供一个T,但需要当前签名才能支持IModelBinder接口 我目前的想

下面有一个类,用于验证用户是否提交了带有无效属性的API请求。我想让这个类成为通用类。例如,我想对任何类型的请求对象通用地使用这个类。例如,UserSearchRequest、GroupSearchRequest、XSearchRequest等

我最初将DeserializeObject的类型显式设置为UserSearchRequest,其工作方式与预期一致,但现在我正在尝试将此实现泛化。我尝试为BindModel()签名提供一个T,但需要当前签名才能支持IModelBinder接口

我目前的想法是让一个类构造函数接受一个类型参数,然后将其设置为一个成员变量,然后在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;
        }
    }
}
使用系统;
使用System.Web.Http.Controller;
使用System.Web.Http.ModelBinding;
使用模型。请求;
使用Newtonsoft.Json;
名称空间MyCorp.Api
{
公共类CustomModelBinder:IModelBinder
{
类型_bindModelType;
公共CustomModelBinder(类型bindModelType)
{
_bindModelType=bindModelType;
}
public bool BindModel(HttpActionContext actionContext,ModelBindingContext bindingContext)
{
var设置=新的JsonSerializerSettings
{
MissingMemberHandling=MissingMemberHandling.Error
};
尝试
{
bindingContext.Model=
JsonConvert.DeserializeObject(
actionContext.Request.Content.ReadAsStringAsync().Result,
设置);
}
捕获(例外情况除外)
{
var split=ex.Message.split(“'.”.ToCharArray());
var message=“{0}.{1}不是有效的属性”;
var formattedMessage=string.Format(消息,拆分[3],拆分[1]);
bindingContext.ModelState.AddModelError(“extraProperty”,formattedMessage);
}
返回true;
}
}
}

是在手机上编写的,可能无法编译,但应该为您指明正确的方向

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;
        }
    }
}
使用系统;
使用System.Web.Http.Controller;
使用System.Web.Http.ModelBinding;
使用模型。请求;
使用Newtonsoft.Json;
名称空间MyCorp.Api
{
公共类CustomModelBinder:IModelBinder
{
public bool BindModel(HttpActionContext actionContext,ModelBindingContext bindingContext)
{
var设置=新的JsonSerializerSettings
{
MissingMemberHandling=MissingMemberHandling.Error
};
尝试
{
bindingContext.Model=
JsonConvert.DeserializeObject(
actionContext.Request.Content.ReadAsStringAsync().Result,
设置);
}
捕获(例外情况除外)
{
var split=ex.Message.split(“'.”.ToCharArray());
var message=“{0}.{1}不是有效的属性”;
var formattedMessage=string.Format(消息,拆分[3],拆分[1]);
bindingContext.ModelState.AddModelError(“extraProperty”,formattedMessage);
}
返回true;
}
}
}

您必须创建一个泛型方法:-这样,您可以使用运行时已知的类型调用泛型方法(不要执行
\u bindModelType.GetType()
,只需使用
\u bindModelType
)@DennisKuypers我尝试过只使用_bindModelType,但返回编译错误:“找不到类型或命名空间名称'\u bindModelType'所以我尝试了typeof(_bindModelType)和_bindModelType.GetType()但是这两种方法都不适用于对象?您可以使用反射来获取
反序列化对象的methodinfo
,然后使用
MakeGenericMethod
使用
\u bindModelType
创建带有类型参数的方法-我会在几分钟后添加一个答案我刚刚看到您不需要泛型,因为您可以将类型传递给非泛型方法<代码>JsonConvert.DeserializeObject(actionContext.Request.Content.ReadAsStringAsync().Result,\u bindModelType,settings)