brillox brillox - 2 months ago 11
C# Question

web api routing with action and id

I am new in using web api and I am trying to call a specific method in my controller.

I have

global.asax

protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}


the WebApiConfig class with these routings

// Web API routes
config.MapHttpAttributeRoutes();


config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new
{
id = RouteParameter.Optional
}
);



config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new
{
action="DefaultAction",
id = RouteParameter.Optional
}
);


and my controller

[HttpGet]
public HttpResponseMessage GetPatSummary(string PatId)
{
PatientSummary Pat = new PatientSummary();

HttpResponseMessage Response = new HttpResponseMessage();
string yourJson = Pat.GetPatient(PatId);
Response = this.Request.CreateResponse(HttpStatusCode.OK, yourJson);
return Response;
}

[ActionName("DefaultAction")] //Map Action and you can name your method with any text
public IHttpActionResult GetPatient(int id)
{
Object Obj = new object();

if (Obj!=null)
{
return NotFound();
}
return Ok(Obj);
}


the URL I am using is

http://localhost/mdmwapi/api/MdmwPatientController/GetPatSummary/sgdgdgddhdhd1334254

but I get this error
A path segment cannot contain two consecutive parameters. They must be separated by a '/' or by a literal string.

I am getting nut :-)

Answer

Use attribute routing

[HttpGet]
[Route("api/MdmwPatientController/GetPatSummary/{PatId}")]
public HttpResponseMessage GetPatSummary(string PatId)
{
    PatientSummary Pat = new PatientSummary();

    HttpResponseMessage Response = new HttpResponseMessage();
    string yourJson = Pat.GetPatient(PatId);
    Response = this.Request.CreateResponse(HttpStatusCode.OK, yourJson);
    return Response;
}

then you can request it using

http://localhost/api/MdmwPatientController/GetPatSummary/yourpatid

also you can map any url using attribute routing this way

Comments