My routing is:
public void RegisterRoute(HttpRouteCollection routes) {
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{guid}",
defaults: new { guid = RouteParameter.Optional }
);
}
controller action is like
public IHttpActionResult Get(Guid guid) {
When I pass api/{controller}/2ADEA345-7F7A-4313-87AE-F05E8B2DE678
everything works fine but when I pass invalid value for guid like
api/{controller}/xxxxxx
then I get error :
{
"message": "The request is invalid.",
"messageDetail": "The parameters dictionary contains a null entry for parameter 'guid' of non-nullable type 'System.Guid' for method 'System.Web.Http.IHttpActionResult Get(System.Guid)' in 'Web.API.Controller.UserController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}
How can I display my own message like:
{
"guid": "The value is invalid.",
}
I'm trying to create custom model binder but it is not working
public class GuidModelBinder : IModelBinder {
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) {
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value == null) {
bindingContext.ModelState.AddModelError("guid", "The value is invalid");
return false;
}
var result = Guid.TryParse(value.ToString(), out _);
if (!result) {
bindingContext.ModelState.AddModelError("guid", "The value is invalid");
}
return result;
}
}
Please help. How can I show only my message