如何使用Http客户端调用MVC Web API动作

时间:2015-09-14 18:36:24

标签: asp.net-mvc asp.net-web-api http-request

我的Http客户端代码是: -

function GetWebApiClient() {
     var client = new HttpClient();
     client.BaseAddress = new Uri(http://localhost:68751);
     client.DefaultRequestHeaders.Accept.Clear();
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
     return client;
}

function sendRequest() {
     using (var client = GetWebApiClient())
     {
          HttpResponseMessage x = await client.GetAsync("api/XYZ/" + somevalue+ "/");
     }
}

控制器代码: -

public class XYZ : ApiController
{
     [System.Web.Mvc.AllowAnonymous]
     public string ABC(string id)
     {
           //need to call this function from client
           return "";
     }
}

每次我发送请求时,都会返回400 Bad request。

1 个答案:

答案 0 :(得分:0)

您的方法名称需要具有“Get”关键字或HttpGet属性,或者它不知道基于您的Http方法执行哪个方法。

public class XYZ : ApiController
{
     [System.Web.Mvc.AllowAnonymous]
     public string GetABC(string id)
     {
         //need to call this function from client
         return "";
     }
}

OR

public class XYZ : ApiController
{
     [System.Web.Mvc.AllowAnonymous]
     [HttpGet]
     public string ABC(string id)
     {
         //need to call this function from client
         return "";
     }
}

请点击此处了解详情:WebApi Routing Documentation