0
votes

My route template on action method is something like below:

[Route("{select:bool=false}")]

and method signature is public int GetMethod(bool select) {}

Question 1:

I am consuming above endpoint by using following url. I am passing string value to boolean parameter

http://localhost/api/controller?select=lskdfj

I get the following response:

{
"Message": "The request is invalid.",
"MessageDetail": "The parameters dictionary contains a null entry for parameter 'select' of non-nullable type 'System.Boolean' for method 'int GetMethod(Boolean)' in '**ProjectName.Controllers.ControllerName**'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}

Instead of showing projectName, controller name which are details of our code and also the above message have more details, I want to show some customize message to consumer/client.

Is there a way to do that?

Question 2:

I am consuming above endpoint by using following url. I am passing by giving incorrect parameter name.

http://localhost/api/controller?selt=true

It does not throw error and take the default value of select i.e. false instead of throwing error.

How to throw error message to the client saying the parameter provided (selt) was wrong?

1

1 Answers

0
votes

Instead of showing projectName, controller name which are details of our code and also the above message have more details, I want to show some customize message to consumer/client.

Option 1

If you want to hide the details of your code, you can just modify the configuration in Global.asax.cs file like this:

GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = 
    IncludeErrorDetailPolicy.Never; // Or Local

Option 2

If you want to customize the message, then you need to "hook" into the processing pipeline and change the response before it goes out the door. To do that, you need to create a Custom Message Handler. Here is something which I quickly put together for you:

public class CustomMessageHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Call the inner handler.
        var response = await base.SendAsync(request, cancellationToken);
        if (response.StatusCode == System.Net.HttpStatusCode.BadRequest &&
            request.RequestUri.ToString().Contains("getmethod"))
        {
            HttpError error = null;
            if (response.TryGetContentValue(out error))
            {
                // Modify the message details
                error.MessageDetail = "Something customized.";
            }
        }
        return response;
    }
}

Register the above message handler in WebApiConfig.cs by adding this line of code:

config.MessageHandlers.Add(new CustomMessageHandler());

Now you will see your custom message instead.