gpt4 book ai didi

c# - 在 ASP.NET Web API 中抑制 JsonMediaTypeFormatter 的 RequiredAttribute 验证

转载 作者:行者123 更新时间:2023-11-30 16:22:22 30 4
gpt4 key购买 nike

假设我向我的 API 发送了以下请求:

POST http://localhost:4940/api/cars HTTP/1.1
User-Agent: Fiddler
Host: localhost:4940
Content-Type: application/json
Content-Length: 44

{"Make":"Make1","Year":2010,"Price":10732.2}

我有以下 Car 类定义:

public class Car {

public int Id { get; set; }

[Required]
[StringLength(20)]
public string Make { get; set; }

[Required]
[StringLength(20)]
public string Model { get; set; }

public int Year { get; set; }

[Range(0, 500000)]
public float Price { get; set; }
}

我得到的回复如下:

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?RTpcRHJvcGJveFxCb29rc1xQcm9XZWJBUEkuU2FtcGxlc1xDaGFwdGVyMTNcRGF0YUFubm90YXRpb25WYWxpZGF0aW9uQXR0cmlidXRlc1NhbXBsZVxEYXRhQW5ub3RhdGlvblZhbGlkYXRpb25BdHRyaWJ1dGVzU2FtcGxlXGFwaVxjYXJz?=
X-Powered-By: ASP.NET
Date: Mon, 17 Sep 2012 11:38:58 GMT
Content-Length: 182

{"Message":"The request is invalid.","ModelState":{"car":["Required property 'Model' not found in JSON. Path '', line 1, position 44."],"car.Model":["The Model field is required."]}}

这是消息正文的更易读的形式:

{
"Message": "The request is invalid.",
"ModelState": {
"car": [
"Required property 'Model' not found in JSON. Path '', line 1, position 44."
],
"car.Model":[
"The Model field is required."
]
}
}

如您所见,我还有一条关于 car 的额外错误消息,我猜测 JsonMediaTypeFormatter 也执行了验证,但未能执行读取操作。

这是这里的问题吗?有什么办法可以抑制 JsonMediaTypeFormatter 级别的验证吗?我不希望格式化程序执行验证,因为验证也是在格式化程序读取消息正文后由 IBodyModelValidator 执行的。

编辑:

我调试了源代码,它发现 JsonMediaTypeFormatter 在属性标记为必需但未提供时抛出错误。以下代码是 JsonMediaTypeFormatter 的一部分:

// Error must always be marked as handled
// Failure to do so can cause the exception to be rethrown at every recursive level and overflow the stack for x64 CLR processes
jsonSerializer.Error += (sender, e) =>
{
Exception exception = e.ErrorContext.Error;
formatterLogger.LogError(e.ErrorContext.Path, exception);
e.ErrorContext.Handled = true;
}

这会触发 ModelStateFormatterLogger.LogError 方法,该方法将错误放入 ModelState 中:

public void LogError(string errorPath, Exception exception)
{
if (errorPath == null)
{
throw Error.ArgumentNull("errorPath");
}
if (exception == null)
{
throw Error.ArgumentNull("exception");
}

string key = ModelBindingHelper.ConcatenateKeys(_prefix, errorPath);
_modelState.AddModelError(key, exception);
}

我仍然无法抑制这种行为。

最佳答案

抱歉,我最初误解了您的问题。好的,这是您需要做的:

创建一个派生自原始 JsonMediaTypeFormatter 的类并设置自定义 IRequiredMemberSelector

public class MyJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public MyJsonMediaTypeFormatter() : base()
{
RequiredMemberSelector = new MyRequiredMemberSelector();
}
}

在此自定义 IRequiredMemberSelector 中,只需将所有属性定义为不需要。

public class MyRequiredMemberSelector : IRequiredMemberSelector
{
public bool IsRequiredMember(System.Reflection.MemberInfo member)
{
return false;
}
}

现在用自定义的替换默认的 JsonMediaTypeFormatter 就可以了。

关于c# - 在 ASP.NET Web API 中抑制 JsonMediaTypeFormatter 的 RequiredAttribute 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12458532/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com