c# - ASP.NET 网络 API : model is valid if error message is set from resources

标签 c# resources asp.net-web-api data-annotations model-validation

问题是在 ApiController 中,如果我使用 .rsx 文件(资源)提供自定义错误消息,ModelState.IsValid 始终是 true

这是我的模型:

public class LoginModel
{
    public string Email { get; set; }

    [Required]
    [MinLength(5)]
    public string Password { get; set; }
}

ApiController 中的方法:

    [HttpPost]
    [ModelValidationFilter]
    public void Post(LoginModel model)
    {
        var a = ModelState.IsValid;
    }

过滤器:

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

我在 POST 请求中发送这个:

{ Email: "asd@asd.com", Password: "a" }

ModelState.IsValidfalse 并且响应符合预期:

{
   "Message": "The request is invalid.",
   "ModelState":
   {
       "model.Password":
       [
           "The field Password must be a string or array type with a minimum length of '5'."
       ]
   }
}

但是如果我在验证属性中使用资源(配置为PublicEmbedded Resource 构建操作):

public class LoginModel
{
    public string Email { get; set; }

    [Required]
    [MinLength(5, ErrorMessageResourceName = "Test", ErrorMessageResourceType = typeof(Resources.Localization))]
    public string Password { get; set; }
}

(“Test”键仅保存“Test”字符串值) ModelState.IsValid 为真。

资源类可见,resharper 正确验证 ErrorMessageResourceName 中提供的字符串。

最佳答案

我尝试了您的解决方案,但我不理解 Resources.Localization 类。它从哪里来的? 我的解决方案如下所述,它使用了很好的资源。

型号:

using TestApp.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace TestApp.Models
{
    public class LoginModel
    {
        public string Email { get; set; }
        [Required]
        [MinLength(5, ErrorMessageResourceName="Test", ErrorMessageResourceType=typeof(Resources))]
        public string Password { get; set; }
    }
}

模型验证过滤器属性:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Net.Http;

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

两个资源文件,一个通用的Resources.resx,包含字符串key/value Test/something;另一个 Resources.de-DE.resx,包含字符串键/值 Test/something_DE。

使用 fiddler 我发送了这个:

Header:
User-Agent: Fiddler
Host: localhost:63315
Content-Length: 37
Content-Type: application/json

正文:

{Email:"text@test.com", Password:"a"}

响应是字符串:

HTTP/1.1 400 Bad Request
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcV29ya1xDU1xGYkJpcnRoZGF5QXBwXEZiQmRheUFwcDJcYXBpXGxvZ2lu?=
X-Powered-By: ASP.NET
Date: Fri, 28 Jun 2013 14:56:54 GMT
Content-Length: 83

{"Message":"The request is invalid.","ModelState":{"model.Password":["something"]}}

对于de-DE,请求头是:

User-Agent: Fiddler
Host: localhost:63315
Content-Length: 37
Accept-Language: de-DE
Content-Type: application/json

响应是:

HTTP/1.1 400 Bad Request
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcV29ya1xDU1xGYkJpcnRoZGF5QXBwXEZiQmRheUFwcDJcYXBpXGxvZ2lu?=
X-Powered-By: ASP.NET
Date: Fri, 28 Jun 2013 14:57:39 GMT
Content-Length: 86

{"Message":"The request is invalid.","ModelState":{"model.Password":["something_DE"]}}

如您所见,消息带有“_DE”,因为它是从本地化资源文件中读取的。

这是您想要实现的目标吗?

亲切的问候。

编辑: 路线配置是

config.Routes.MapHttpRoute(
          name: "LoginRoute",
          routeTemplate: "api/login",
          defaults: new { controller = "Login", action = "PostLogin" },
          constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) }
          );

Web.config 添加了下一部分:

<system.web>
...
        <globalization culture="auto" uiCulture="auto" />
...
</system.web>

关于c# - ASP.NET 网络 API : model is valid if error message is set from resources,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17338864/

相关文章:

resources - 将 CouchDB 中的资源访问限制为恰好 2 个用户

routes - Web api路由: optional parameters

c# - 谷歌表 API V4 : Unable to fetch cell note in Google Sheet

c# - 无法向 Google 电子表格添加行

c# - 在 .net WinForms ListView 中获取 ColumnHeaders 的高度(在细节模式下)

c# - C#中不用foreach直接获取dictionary<int, object>第一个key

qt - 在 Qt Creator 构建目录中包含资源文件

c++ - 是什么激发了 Stroustrup 对资源管理技术的偏好顺序?

c# - 为什么Web Api(.Net Core)总是返回JSON而忽略ContentType中的值?

javascript - 通过 javascript 将复杂参数传递给 Web API 服务