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

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

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

每当我用上面的代码调用此网站 API 时,它都会转到第一个 get 方法。 但我不会调用第二种方法

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,因为您可以使用用于创建 Guid 实例的相同字符串构建 URL [=15] =]