Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
        }
    }
}
like image 713
NullReference Avatar asked Oct 27 '25 00:10

NullReference


1 Answers

Try to use:

[HttpGet]
public User Get(Guid? Id = null)
like image 196
MuriloKunze Avatar answered Oct 28 '25 22:10

MuriloKunze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!