gpt4 book ai didi

c# - 如何区分空的可空 Guid 或查询字符串中的无效 Guid?

转载 作者:太空宇宙 更新时间:2023-11-03 12:48:32 34 4
gpt4 key购买 nike

上下文:ASP.NET Web API v2

给定一个类似于这个的 URL:

http://localhost/something?id=cbc66d32-ece8-400f-a574-e36b911e1369

当网络方法像这样定义“id”查询字符串参数时:

[FromUri] Guid? id = null

然后调用 web 方法,无论 Guid 是无效的东西,如“asdf”还是完全省略,id 变量都会被填充为 null。


我们需要在无效的 Guid 上向客户端抛出 HTTP 400,但对空的 Guid 进行一些有效的通用处理。这些是非常不同的结果。因此,我们需要区分它们,但在方法调用时获得相同的输入。

是否有一种有效的方法来配置 ASP.NET Web API,以便它在所有无效的 Guid 上发出 HTTP 400?我们经常使用可为 null 的 Guid,并且每次都期待这种行为。

最佳答案

您可以使用自定义模型绑定(bind)器

public IHttpActionResult Get([ModelBinder(typeof(GuidParserModelBinder))] Guid? id = null)
{
return Json(id);
}

public class GuidParserModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext,
ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof (Guid?))
return false;

var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var rawValue = value.RawValue.ToString();

if (string.IsNullOrWhiteSpace(rawValue))
return false;

Guid guid;
if (Guid.TryParse(rawValue, out guid))
{
bindingContext.Model = guid;
return true;
}

// throw exception or logic here
return false;
}
}

关于c# - 如何区分空的可空 Guid 或查询字符串中的无效 Guid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36436673/

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