asp.net-mvc - 具有可为空 Guid 的 Web Api GET 方法可能吗?

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

我有一个 MVC Web API get 方法,我希望能够将一个可为空的 Guid 作为参数传递。如果我使用 "?Id=null"设置 GET,我会收到 400 响应。我可以传递一个空的 guid,但我宁愿不这样做。

无论我将 URI 更改为“id=、id=null 等”,它都不会接受 null。有谁知道如何使这项工作?

  [HttpGet]
  public User Get(Guid? Id)

更新路由配置
  config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

Full Http Get 签名,sourceId 是id 喜欢传null 的参数。
 [HttpGet]
  public IEnumerable<ActionItemsListViewModel> GetPagedList(int skip, int take, int page, int pageSize, [FromUri]List<GridSortInfo> sort, [FromUri] ActionItem.ActionItemStatusTypes? actionItemStatus, Guid? sourceId)

发现问题,这个过滤器说 ModelState 无效。
public class ApiValidationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid )
        {
            var errors = actionContext.ModelState
                .Where(e => e.Value.Errors.Count > 0)
                .Select(e => e.Value.Errors.First().ErrorMessage).ToList();

            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, string.Join(" ", errors));
        }
    }
}

最佳答案

尝试使用:

[HttpGet]
public User Get(Guid? Id = null)

关于asp.net-mvc - 具有可为空 Guid 的 Web Api GET 方法可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12827815/

相关文章:

jquery - 在 MVC 3 中,如果不显眼的验证无效则显示 div,如果有效则隐藏它

c# - 尝试创建类型的 Controller 时出错。确保 Controller 有一个无参数的公共(public)构造函数

c# - 向现有 WebAPI 添加版本控制

javascript - SignalR 的跨域协商请求错误

asp.net - ASP.NET Web Api 中的 Swashbuckle 被嵌套 Controller 混淆

asp.net-mvc - ASP.NET MVC 未正确加载 FontAwesome(模糊)

c# - MVC 5、EF 6 Barebones 无效的列名称 'Model'

c# - WebAPI 文件上传 - 无需将文件写入磁盘

c# - 验证数据模型

asp.net-mvc - Windows Azure 角色持续回收并出现 Microsoft-Windows-WAS 警告