2

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

6

2 Answers 2

4

You can do it by making your Guid a Nullable<Guid> and do a null check:

public IHttpActionResult Get(Guid? guid) { if(!guid.HasValue || guid.Value == Guid.Empty) // return your error here else //... } 
Sign up to request clarification or add additional context in comments.

1 Comment

I have many actions. I can't change every action. Are there any other ways?
1

Close but BindModel must return a Guid. Since your parameter is a guid, which is a value type, it MUST have a non-null value. In the example below, I used Guid.Empty as the value if the passed-in value is not a parsable guid.

This will allow IIS to call your controller with the Guid.Empty value and the Model error you specified.

public class GuidModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); Guid guidValue; if (value == null || !Guid.TryParse(value.AttemptedValue, out guidValue)) { bindingContext.ModelState.AddModelError("guid", "The value is invalid"); return Guid.Empty; } return guidValue; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.