如何在web api 2中使用相同参数的get方法使用属性路由

时间:2018-01-18 14:14:33

标签: c# asp.net asp.net-mvc-4 asp.net-web-api asp.net-web-api-routing

以下是调用Web API调用的代码

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);
}
以下

是网络API方法

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);
}

每当我使用上面的代码调用此Web API时,它都会转到第一个get方法。 但我不会打电话给第二种方法

1 个答案:

答案 0 :(得分:0)

Web API上的路由是

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

然而请求正在调用

"api/ApplicationSIRMeasure/RequisitionNameByQuantity?applicationRequisitionOid="

由于url与第二个路由模板不匹配,因此查找其他操作的匹配项,因为查询字符串参数匹配。

您需要更新被调用的URL以匹配目标操作的路由模板。

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

当你可以使用与创建Guid实例相同的字符串构建URL时,我真的不认为需要创建Guid