简体   繁体   中英

How to differentiate an empty nullable Guid or an invalid one in a querystring?

Context: ASP.NET Web API v2

Given an URL similar to this one:

http://localhost/something?id=cbc66d32-ece8-400f-a574-e36b911e1369

When the web method defines an "id" querystring parameter like this:

 [FromUri] Guid? id = null

Then the web method gets called, whether the Guid is an invalid thing such as "asdf" or is completely ommited, the id variable gets filled with null.


We need to throw a HTTP 400 to the client on an invalid Guid, but do some valid generic processing on a null one. Those are very different outcomes. We thus need to differentiate them but get the same input on the method call.

Is there an efficient way to configure ASP.NET Web API so that it issues a HTTP 400 on invalid Guids all over the board? We use nullable Guids quite often and are expecting this kind of behaviour every time.

You can use a custom Model Binder

public IHttpActionResult Get([ModelBinder(typeof(GuidParserModelBinder))] Guid? id = null)
{
    return Json(id);
}

public class GuidParserModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, 
        ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof (Guid?))
            return false;

        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        var rawValue = value.RawValue.ToString();

        if (string.IsNullOrWhiteSpace(rawValue))
            return false;

        Guid guid;
        if (Guid.TryParse(rawValue, out guid))
        {
            bindingContext.Model = guid;
            return true;
        }

        // throw exception or logic here
        return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM