Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.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#_Asp.net_Validation_Asp.net Web Api2_Owin - Fatal编程技术网

C# 模型验证不适用于自托管web api应用程序中的字段

C# 模型验证不适用于自托管web api应用程序中的字段,c#,asp.net,validation,asp.net-web-api2,owin,C#,Asp.net,Validation,Asp.net Web Api2,Owin,最近,我们想在现有的WebAPI项目中添加使用数据注释方法的逻辑。我们发现,一些验证属性不适用于模型的字段,但适用于属性: public class SomeController : ApiController { static void Main(string[] args) { WebApp.Start("http://*:80/", app => { HttpConfiguration cfg = new Htt

最近,我们想在现有的WebAPI项目中添加使用数据注释方法的逻辑。我们发现,一些验证属性不适用于模型的字段,但适用于属性:

public class SomeController : ApiController
{
    static void Main(string[] args)
    {
        WebApp.Start("http://*:80/", app =>
        {
            HttpConfiguration cfg = new HttpConfiguration();
            cfg.MapHttpAttributeRoutes();
            app.UseWebApi(cfg);
        });

        Console.WriteLine("The server has been started");
        Console.ReadLine();
    }

    [ValidateModel]
    [Route]
    public void Post([FromBody]Model model)
    {
        string p = model == null ? "model is null" :
                   string.IsNullOrEmpty(model.Required) ? "required is null" : 
                   model.Required;
        Console.WriteLine($"Passed model is: {p}");
    }
}

public class Model
{
    [Required(AllowEmptyStrings = false)]
    public string Required; // Model validation does not works
    //public string Required { get; set; } - Model validation works
}

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid == false)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}

POST http://localhost/ HTTP/1.1
User-Agent: Fiddler
Host: sb1124
Content-Length: 23
Content-Type: application/json

{
    "wtf" : "ftw"
}
给我们:

HTTP/1.1 204 No Content
Content-Length: 0
Server: Microsoft-HTTPAPI/2.0
Date: Tue, 24 May 2016 05:54:43 GMT
这看起来像是不正确的行为,IMHO,尽管文章指出:

在ASP.NET Web API中,可以使用System.ComponentModel.DataAnnotations命名空间中的属性为模型上的属性设置验证规则

我已尝试从RequiredAttribute创建嵌套验证属性,并重写
IsValid
方法,但断点未命中。一种解决方法是修改模型以使用属性

为什么这个设计决策只验证属性,而不验证字段?是否有任何其他解决方法可以帮助避免模型更改


要执行此控制台应用程序,请使用Packcage管理器控制台:

Install-Package Microsoft.AspNet.WebApi
Install-Package Microsoft.Owin.Hosting
Install-Package Microsoft.Owin.Host.HttpListener