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));
}
}
}
Try to use:
I was able to pass null to the Guid? when I use
Controller: