简体   繁体   English

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

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

following is code for calling web API call 以下是调用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);
}

below is web API methods 以下是Web 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);
}

whenever I call this web API with above code it goes to first get method. 每当我用上面的代码调用此Web API时,它都会转到第一个get方法。 but I won't to call in a second method 但我不会调用第二种方法

The route on the Web API is Web API上的路由为

[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. 您需要更新所调用的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);

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 我真的不认为有必要创建Guid时,你可以建立URL与用于创建相同的字符串Guid实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM