【问题标题】:How to differentiate an empty nullable Guid or an invalid one in a querystring?如何区分查询字符串中空的可为空的 Guid 或无效的 Guid?
【发布时间】:2016-04-05 20:43:26
【问题描述】:

上下文:ASP.NET Web API v2

给定一个与此类似的 URL:

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

当 web 方法定义一个像这样的“id”查询字符串参数时:

[FromUri] Guid? id = null

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


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

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

【问题讨论】:

  • id parameter 作为字符串而不是Guid? 怎么样,如果它是空的,那就是你的空情况。如果不是,则尝试解析,并可以验证它是否是有效的 Guid。
  • 它确实可以工作,但我们必须在每个方法调用上使用可为空的 guid 作为查询字符串编写该代码。此外,我们有一个自动文档工具,它不知道这个参数应该是一个 Guid,具体来说。
  • 您能否重载 id 属性并将 'asdf' 视为字符串,同时仍能正确捕获 guid? stackoverflow.com/questions/14353466/…
  • 您可以使用@Merryweather 建议的字符串并将逻辑放入操作过滤器中,您只需在要检查的每个操作上方添加操作过滤器
  • 自定义model binder怎么样,你在哪里做这种逻辑?你只需要写一次。

标签: c# asp.net asp.net-web-api2 query-string guid


【解决方案1】:

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

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;
    }
}

【讨论】:

  • 可能是一个好的开始。 ModelBinder 中的查询字符串键不应被硬编码,因为某些 Guid 可能与其他 Guid 相关联。
  • @RooSoft 您没有在问题中提到需要这种类型的灵活性,也没有关系。您可以使用 bindingContext.ModelName,正如我在回答中更新的那样。
猜你喜欢
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多