c# - 验证 GUID 作为参数

标签 c# asp.net asp.net-mvc asp.net-web-api

我的路线是:

public void RegisterRoute(HttpRouteCollection routes) {
    routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{guid}",
        defaults: new { guid = RouteParameter.Optional }
    );
}

Controller Action 就像

public IHttpActionResult Get(Guid guid) {

当我传递api/{controller}/2ADEA345-7F7A-4313-87AE-F05E8B2DE678时,一切正常,但是当我传递无效的guid值时,例如

api/{controller}/xxxxxx 然后我收到错误:

{
  "message": "The request is invalid.",
  "messageDetail": "The parameters dictionary contains a null entry for parameter 'guid' of non-nullable type 'System.Guid' for method 'System.Web.Http.IHttpActionResult Get(System.Guid)' in 'Web.API.Controller.UserController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}

如何显示我自己的消息,例如:

{
  "guid": "The value is invalid.",
}

我正在尝试创建自定义模型绑定(bind)程序,但它不起作用

public class GuidModelBinder : IModelBinder {

        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (value == null) {
                bindingContext.ModelState.AddModelError("guid", "The value is invalid");
                return false;
            }


            var result = Guid.TryParse(value.ToString(), out _);
            if (!result) {
                bindingContext.ModelState.AddModelError("guid", "The value is invalid");
            }
            return result;
        }
    }

请帮忙。如何只显示我的消息

最佳答案

您可以通过创建 Guid 来做到这一点一个Nullable<Guid>并执行 null检查:

public IHttpActionResult Get(Guid? guid) {

    if(!guid.HasValue || guid.Value == Guid.Empty)
        // return your error here

    else
    //...
}

关于c# - 验证 GUID 作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44762673/

相关文章:

c# - 防止在 IIS 中加载特定的 dll

c# - Process.Startinfo 从 ASP.NET 打印 PDF 在 Windows Server 2003 中不起作用

asp.net - 打印预览中不显示图表区域

c# - 处理存储库中未找到的对象

asp.net-mvc - 在 MVC.NET 中测试 User.IsInRole

asp.net-mvc - HTML 5 实时数据

C# 如何将不仅仅是 IAsyncResult 传递给 AsyncCallback?

c# - 如何将此脚本重写为 C# (Unity)?

c# - SSL 证书 : A specified logon session does not exist

asp.net-mvc - Paypal Payflow 链接 ASP.Net MVC 开源框架