可能具有可为空Guid的Web Api GET方法? [英] Web Api GET method that has a nullable Guid possible?

查看:101
本文介绍了可能具有可为空Guid的Web Api GET方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a MVC Web API get method that I'd like to be able to pass a nullable Guid as a parameter. If I setup the GET with a "?Id=null" I get a 400 response. I can pass a empty guid but that I'd rather not do that.

无论我将URI更改为"id =,id = null等",它都不会接受null.有人知道如何使这项工作吗?

No matter what I change the URI to, "id=, id=null etc" it won't accept null. Does anyone know how to make this work?

  [HttpGet]
  public User Get(Guid? Id)

更新路由配置

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

完整的Http获取签名,sourceId是id希望作为null传递的参数.

Full Http Get signature, sourceId is the param that id like to pass as 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无效.

Found the problem, this filter was saying the ModelState was invalid.

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

推荐答案

我能够将null传递给Guid吗?当我使用

I was able to pass null to the Guid? when I use

  • 查询字符串参数:api/values?id = null
  • 路由参数:api/values/null

控制器:

 public class ValuesController : ApiController
 {
     public User Get(Guid? Id)
     { ... }
 }

这篇关于可能具有可为空Guid的Web Api GET方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆