Web Api GET method that has a nullable Guid possib

2019-08-10 19:16发布

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.

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)

Update Route config

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

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)

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

2条回答
2楼-- · 2019-08-10 20:20

Try to use:

[HttpGet]
public User Get(Guid? Id = null)
查看更多
Bombasti
3楼-- · 2019-08-10 20:21

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

  • query string parameter: api/values?id=null
  • route parameter: api/values/null

Controller:

 public class ValuesController : ApiController
 {
     public User Get(Guid? Id)
     { ... }
 }
查看更多
登录 后发表回答