Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.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# 自定义验证器属性在单元测试中有效,但在web api控制器中无效?_C#_Data Annotations_Asp.net Core Webapi_Asp.net Core Webapi 2.1 - Fatal编程技术网

C# 自定义验证器属性在单元测试中有效,但在web api控制器中无效?

C# 自定义验证器属性在单元测试中有效,但在web api控制器中无效?,c#,data-annotations,asp.net-core-webapi,asp.net-core-webapi-2.1,C#,Data Annotations,Asp.net Core Webapi,Asp.net Core Webapi 2.1,ValidateMinMaxListCountAttribute验证属性在我的单元测试中有效,但在web api框架中使用时无效 例如,在单元测试中,“isValid”返回true,但在控制器中失败。我猜是某种序列化问题 有人有什么想法吗 [TestCategory("ServiceTests")] [TestMethod] public void CallServiceCalc() { var client = new RestClient(); client.BaseUrl

ValidateMinMaxListCountAttribute验证属性在我的单元测试中有效,但在web api框架中使用时无效

例如,在单元测试中,“isValid”返回true,但在控制器中失败。我猜是某种序列化问题

有人有什么想法吗

[TestCategory("ServiceTests")]
[TestMethod]
public void CallServiceCalc()
{

    var client = new RestClient();
    client.BaseUrl = new Uri("https://localhost:44379");
    client.Authenticator = new HttpBasicAuthenticator("eric.schneider", "password");

    var request = new RestRequest();
    request.Resource = "api/Calculation/Calculate";

    CoralRequest coralReq = new CoralRequest();
    coralReq.ModelId = 1;
    coralReq.ModelName = "2018";
    coralReq.BasePlan = new BeneifitsPlanInputs();
    coralReq.Plans.Add(new BeneifitsPlanInputs());
    request.AddBody(coralReq);

    ValidateMinMaxListCountAttribute va = new ValidateMinMaxListCountAttribute(1, 999);
    bool isValid = va.IsValid(coralReq.Plans);

    IRestResponse response = client.Execute(request);

    Assert.IsTrue(response.StatusCode == System.Net.HttpStatusCode.OK, "Should not be ok");
}

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ValidateMinMaxListCountAttribute : ValidationAttribute
{
    public ValidateMinMaxListCountAttribute(int minimum, int maximum)

{
    this.MinimumCount = minimum;
    this.MaximumCount = maximum;
}

public int MinimumCount { get; set; }
public int MaximumCount { get; set; }

public override bool IsValid(object value)
{
    var list = value as ICollection;

    if (list != null)
    {
        if (list.Count > MaximumCount) { return false; }
        if (list.Count < MinimumCount) { return false; }
        return true;
        }

        return false;
    }
}


   public class CoralRequest
    {
        public CoralRequest()

    {
        this.Plans = new List<BeneifitsPlanInputs>();
    }


    /// <summary>
    /// 
    /// </summary>
    [ValidateMinMaxListCount(1, 99, ErrorMessage = "Must have between 1 and 99 plans")]
    public IList<BeneifitsPlanInputs> Plans { get; set; }
}
[TestCategory(“ServiceTests”)]
[测试方法]
public void CallServiceCalc()
{
var client=new RestClient();
client.BaseUrl=新Uri(“https://localhost:44379");
client.Authenticator=新的HttpBasicAuthenticator(“eric.schneider”,“password”);
var request=new RestRequest();
request.Resource=“api/Calculation/Calculation”;
CoralRequest CoralRequest=新的CoralRequest();
coralReq.ModelId=1;
coralReq.ModelName=“2018”;
coralReq.BasePlan=新的BeneifitsPlanInputs();
coralReq.Plans.Add(新BeneifitPlanInputs());
请求。AddBody(coralReq);
ValidateMinMaxListCountAttribute va=新的ValidateMinMaxListCountAttribute(1999);
bool isValid=va.isValid(珊瑚礁均衡计划);
IRestResponse response=client.Execute(请求);
Assert.IsTrue(response.StatusCode==System.Net.HttpStatusCode.OK,“不应该是OK”);
}
[AttributeUsage(AttributeTargets.Property,AllowMultiple=false)]
公共类ValidateMinMaxListCountAttribute:ValidationAttribute
{
公共ValidateMinMaxListCountAttribute(最小整数、最大整数)
{
此项。最小计数=最小值;
此参数。MaximumCount=最大值;
}
公共int最小计数{get;set;}
公共int最大计数{get;set;}
公共覆盖布尔值有效(对象值)
{
var list=作为ICollection的值;
如果(列表!=null)
{
如果(list.Count>MaximumCount){return false;}
if(list.Count
根据您的另一个问题(似乎是相关的),您可以显示控制器操作看起来像

[HttpGet("{mock}")]
public ActionResult<CoralResult> CalculateMock(CoralRequest mock)
[HttpGet(“{mock}”)]
公共操作结果CalculateMock(CoralRequest模拟)
在测试中,发出GET请求时,GET请求没有主体,但是您向请求中添加了一个主体。这意味着在服务器上很可能没有正确填充/绑定模型

这看起来很经典

如果您想要获取请求的主体,那么该操作很可能是POST请求,并且该操作应该被重构,以明确地说明从何处获取数据

[Route("api/[controller]")]
public class CalculationController: Controller {

    //POST api/Calculation/Calculate
    [HttpPost("[action]")]
    public ActionResult<CoralResult> Calculate([FromBody]CoralRequest model) {
        if(ModelState.IsValid) {
            CoralResult result = new CoralResult();

            //...do something with model and populate result.

            return result;
        }
        return BadRequest(ModelState);
    }

}
[路由(“api/[控制器]”)]
公共类计算控制器:控制器{
//后api/计算/计算
[HttpPost(“[行动]”)]
公共行动结果计算([FromBody]CoralRequest模型){
if(ModelState.IsValid){
CoralResult结果=新的CoralResult();
//…对模型执行某些操作并填充结果。
返回结果;
}
返回请求(ModelState);
}
}
现在应该与集成测试中尝试的内容更加匹配

[TestCategory("ServiceTests")]
[TestMethod]
public void CallServiceCalc() {

    var client = new RestClient();
    client.BaseUrl = new Uri("https://localhost:44379");
    client.Authenticator = new HttpBasicAuthenticator("eric.schneider", "password");

    var request = new RestRequest(Method.POST); //<-- POST request
    request.Resource = "api/Calculation/Calculate";
    request.AddHeader("content-type", "application/json");

    CoralRequest coralReq = new CoralRequest();
    coralReq.ModelId = 1;
    coralReq.ModelName = "2018";
    coralReq.BasePlan = new BeneifitsPlanInputs();
    coralReq.Plans.Add(new BeneifitsPlanInputs());
    request.AddJsonBody(coralReq); //<-- adding data as JSON to body of request

    IRestResponse response = client.Execute(request);

    Assert.IsTrue(response.StatusCode == System.Net.HttpStatusCode.OK, "Should be HttpStatusCode.OK");
}
[TestCategory(“ServiceTests”)]
[测试方法]
public void CallServiceCalc(){
var client=new RestClient();
client.BaseUrl=新Uri(“https://localhost:44379");
client.Authenticator=新的HttpBasicAuthenticator(“eric.schneider”,“password”);

var request=new RestRequest(Method.POST);//您所说的“在web api框架中不工作”是什么意思?我的控制器类验证并说它是一个错误的请求,属性存在验证错误。对于
一个错误的请求
,它不会验证模型。如果你在
ValidateMinMaxListCountAttribute
上设置断点,从web api调用时它会被击中吗?请共享你的客户端请求。我确实共享了它;我正在调用正如我在单元测试中所说的,我添加了ValidateMinMaxListCountAttribute的测试调用,它可以工作,并且可以调试。但是mvc框架调用不能进行验证,它必须进行验证,因为我得到验证错误消息“必须有1到99个计划”,但我确实有一个计划在那里。。。