Question

In WebApiConfig I have following:

config.Routes.MapHttpRoute("Alerts", "alerts/{username}/{scope}/{language}",new { controller = "Alerts", language = RouteParameter.Optional });

In my AlertsController I have this:

public async Task<HttpResponseMessage> GetAsync(string username, string scope, string language = "en")
    {

        if (string.IsNullOrWhiteSpace(username))
        {
            return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Username cannot be null.");
        }

        if (string.IsNullOrWhiteSpace(scope))
        {
            return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Scope cannot be null.");
        }

        var scp = this._scopeFactory.GetScope(scope);
        var alerts = await scp.GetAlerts(username, scope).ConfigureAwait(false);

        return this.Request.CreateResponse(HttpStatusCode.OK, alerts);
    }

What I want to achieve, is when I type in my browser http://www.localhost.com/alerts (without giving a username and scope) to see "Username cannot be null" and "Scope cannot be null" in json format.

Right now I get Resource not found, which makes sense since the router can not match such a resource. Do you know if is possible to achieve what I want with some Configuration change (or maybe something else)?

Was it helpful?

Solution

I had to set nullable parameters to make this work.

public async Task<HttpResponseMessage> GetAsync(string username = null, string scope = null, string language = "en")

In WebApiConfig I had to make them optional as well:

config.Routes.MapHttpRoute("Alerts", "alerts/{username}/{scope}/{language}",new { controller = "Alerts", username = RouteParameter.Optional, scope = RouteParameter.Optional, language = RouteParameter.Optional });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top