2015-09-14 42 views
0

我的HTTP客户端的代码是: -如何使用HTTP客户端调用的MVC Web API行动

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错误的请求。

+0

不应该有围绕在新的URI(您的网址...一行的双引号会不会是那么简单?因为你的控制器方法被称为ABC,但是你正在调用api/XYZ? –

+0

尝试为'id'参数添加'FromUri'属性,也可以参考这个链接http://www.asp.net/web-api/ overview/advanced/calling-a-web-api-from-a-net-client – Karthik

回答

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

+0

Thanks.I was using the authentic在apiController函数中使用MVC,这就是为什么它不起作用。我将它改为HTTP然后它对我有用。 – user3894514