NullReference
NullReference

Reputation: 4484

Web Api GET method that has a nullable Guid possible?

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

Upvotes: 4

Views: 9000

Answers (2)

Maggie Ying
Maggie Ying

Reputation: 10185

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)
     { ... }
 }

Upvotes: 1

MuriloKunze
MuriloKunze

Reputation: 15593

Try to use:

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

Upvotes: 4

Related Questions