Search code examples
c#asp.netasp.net-mvc-4asp.net-web-apiasp.net-web-api-routing

How to use attribute routing in for get method with same parameter in web api 2


following is code for calling web API call

public async System.Threading.Tasks.Task<ActionResult> RequisitionNameByQuantityThisDraw()
{
    //Guid applicationRequisitionOid

    string userName = string.Empty;
    SessionObject sessionData = new SessionObject().GetSessionData();
    if (sessionData == null)
    {
        return RedirectToAction("UserLogin", "Login");
    }
    Guid aa = new Guid("41CF8843-2AF4-40D0-9998-D6D516367A7D");
    HttpResponseMessage response = _HttpClient.GetAsync("api/ApplicationSIRMeasure/RequisitionNameByQuantity?applicationRequisitionOid=" + aa).Result;

    string userJsonString = await response.Content.ReadAsStringAsync();
    return Json(userJsonString, JsonRequestBehavior.AllowGet);
}

below is web API methods

public HttpResponseMessage Get(Guid applicationRequisitionOid)
{
    var result = _IService.GetAll(applicationRequisitionOid);
    if (result == null)
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No data found");
    else
        return Request.CreateResponse(HttpStatusCode.OK, result);
}   

[Route("api/ApplicationSIRMeasure/RequisitionNameByQuantity/{applicationRequisitionOid:Guid}")]
public HttpResponseMessage RequisitionNameByQuantity(Guid applicationRequisitionOid)
{
    Guid id = new Guid("41CF8843-2AF4-40D0-9998-D6D516367A7D");
    var result = _IService.GetRequisitionByQunatityThisDraw(id);
    if (result == null)
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No data found");
    else
        return Request.CreateResponse(HttpStatusCode.OK, result);
}

whenever I call this web API with above code it goes to first get method. but I won't to call in a second method


Solution

  • The route on the Web API is

    [Route("api/ApplicationSIRMeasure/RequisitionNameByQuantity/{applicationRequisitionOid:guid}")]
    

    Yet the request is calling

    "api/ApplicationSIRMeasure/RequisitionNameByQuantity?applicationRequisitionOid="
    

    Because the url does not match the second route template it is finding a match on the other action because the query string parameter matches.

    you need to update the URL being called to match the route template of the target action.

    var aa = new Guid("41CF8843-2AF4-40D0-9998-D6D516367A7D");
    var url = string.Format("api/ApplicationSIRMeasure/RequisitionNameByQuantity/{0}", aa);
    var response = await _HttpClient.GetAsync(url);
    

    I really do not see the need to create the Guid when you can just build the URL with the same string that was used to create the Guid instance