gpt4 book ai didi

c# - 在 Web API 中没有发布数据时避免空模型

转载 作者:太空狗 更新时间:2023-10-30 00:40:22 26 4
gpt4 key购买 nike

这题和我想实现的类似:

Avoiding null model in ASP.Net Web API when no posted properties match the model

但无人回答。

我有一条路线采用 GET 模型:

    [HttpGet, Route("accounts")]
public AccountListResult Post(AccountListRequest loginRequest)
{
return accountService.GetAccounts(loginRequest);
}

该模型填充了来自操作过滤器的附加数据。

在这种情况下,所有需要知道的是 UserId,操作过滤器将其添加到基于 cookie/header 的模型中,随请求一起传递。

我想在 WebAPI 中使用所有默认模型绑定(bind),但我想避免空对象。

我不相信模型绑定(bind)可以解决我的问题。

How do I replace the behaviour of Web API model binding so that instead of Null I receive a new instance when no parameters are passed in

这更接近我想做的,除了它的每种类型都很乏味。

最佳答案

编辑:由于问题是针对 Web API 的,因此我也在下面发布了 Web API 解决方案。

您可以在 Action 过滤器中按以下方式执行此操作。以下代码仅在您的模型包含默认构造函数时才有效。

网络 API 实现:

public override void OnActionExecuting(HttpActionContext actionContext)
{
var parameters = actionContext.ActionDescriptor.GetParameters();

foreach (var parameter in parameters)
{
object value = null;

if (actionContext.ActionArguments.ContainsKey(parameter.ParameterName))
value = actionContext.ActionArguments[parameter.ParameterName];

if (value != null)
continue;

value = CreateInstance(parameter.ParameterType);
actionContext.ActionArguments[parameter.ParameterName] = value;
}

base.OnActionExecuting(actionContext);
}

protected virtual object CreateInstance(Type type)
{
// Check for existence of default constructor using reflection if needed
// and if performance is not a constraint.

// The below line will fail if the model does not contain a default constructor.
return Activator.CreateInstance(type);
}

MVC 实现:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var parameters = filterContext.ActionDescriptor.GetParameters();

foreach (var parameter in parameters)
{
if (filterContext.ActionParameters.ContainsKey(parameter.ParameterName))
{
object value = filterContext.ActionParameters[parameter.ParameterName];

if (value == null)
{
// The below line will fail if the model does not contain a default constructor.
value = Activator.CreateInstance(parameter.ParameterType);
filterContext.ActionParameters[parameter.ParameterName] = value;
}
}
}

base.OnActionExecuting(filterContext);
}

关于c# - 在 Web API 中没有发布数据时避免空模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28430031/

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