nari447
nari447

Reputation: 914

can we pass null in the url parameter?

I have a Asp.Net webApi controller as below:

[RoutePrefix("business/api/v1")]
public class BusinessController : ApiController
{


    [Route("GetDetails/{id}")]
    public HttpResponseMessage Get(string id)
    { 
        // get business details code.
      } 
  }

Is there anyway that client can hit this api with id null??

Upvotes: 2

Views: 4866

Answers (2)

Fan TianYi
Fan TianYi

Reputation: 417

Please try:

[RoutePrefix("business/api/v1")]
public class BusinessController : ApiController
{       
    [Route("GetDetails/{id:int?}")]
    public HttpResponseMessage Get(int id)
    { 
        // get business details code.
    } 
}

Upvotes: 2

Roman Marusyk
Roman Marusyk

Reputation: 24569

It depends on your configuration of Web API routes in App_Start/WebApiConfig.cs.

If route is something like:

  config.Routes.MapHttpRoute(
       name: "DefaultApi",
       routeTemplate: "business/api/v1/GetDetails/{id}",
       defaults: new { id = RouteParameter.Optional }
  );

then user can reach resource use http://localhost.business/api/v1/GetDetails or http://localhost.business/api/v1/GetDetails/1.

When you remove defaults: new { id = RouteParameter.Optional } then user have to pass an id otherwise, it will return 404

Upvotes: 3

Related Questions