HttpClient使用asp.net mvc应用程序发布WebApi请求

时间:2016-08-25 07:47:32

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

我正在尝试使用WebApi,但我遇到了问题。我的'IsSuccessStatusCode'总是假的,我有404响应。

我尝试了多种方法,但无法正确完成。

常量:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(baseUri);

    var content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("deadId", "3"),
        new KeyValuePair<string, string>("flagValueToSet", "true")
    });

    var response = await client.PostAsync(setDealFlagUri, content);
    if (response.IsSuccessStatusCode)
    {
        return true;
    }
}

方法1,使用PostAsync:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(baseUri);
    DealFlag content = new DealFlag
    {
        deadId = 3,
        flagValueToSet = true
    };

    var response = await client.PostAsJsonAsync(setDealFlagUri, content);
    if (response.IsSuccessStatusCode)
    {
        return true;
    }
}

方法2,使用PostAsJsonAsync:

{
  "Successful": true,
  "ErrorMessages": [],
  "ValidationResults": {
    "IsValid": false,
    "ValidationErrors": []
  }
}

WebApi请求详细信息:

卷曲:

  

curl -X POST --header'Eccept:application / json''{baseApiurl} / Deals / SetDealFlag?dealId = 3&amp; flagValueToSet = true'

请求网址

  

{baseApiurl} /减/ SetDealFlag dealId = 3&安培; flagValueToSet =真

回应机构

{
  "pragma": "no-cache",
  "date": "Wed, 24 Aug 2016 18:38:01 GMT",
  "content-encoding": "gzip",
  "server": "Microsoft-IIS/8.0",
  "x-aspnet-version": "4.0.30319",
  "x-powered-by": "ASP.NET",
  "vary": "Accept-Encoding",
  "content-type": "application/json; charset=utf-8",
  "cache-control": "no-cache",
  "content-length": "198",
  "expires": "-1"
}

响应标头

$dispatcher = new Phroute\Phroute\Dispatcher($router->getData());
echo $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

请帮我正确使用此webapi功能。 谢谢!

1 个答案:

答案 0 :(得分:2)

我认为问题在于您的控制器方法具有类似

的签名
[HttpPost]
public HttpResponseMessage SetDealFlag(int dealId, bool flagValueToSet)

我是对的吗?如果您的回答是&#34;是&#34;所以你的方法需要URL中的参数。

所以你得到404错误,因为你的Web API方法没有一个与该URL匹配。

在网址中发送您的参数dealIdflagValueToSet是解决方案。

我编写了简单的控制台应用程序来测试我的理论,它运作得很好:

public static void Main(string[] args)
{
  using (var client = new HttpClient())
  {
    try
    {
      // Next two lines are not required. You can comment or delete that lines without any regrets
      const string baseUri = "{base-url}";
      client.BaseAddress = new Uri(baseUri);

      var content = new FormUrlEncodedContent(new[]
      {
        new KeyValuePair<string, string>("deadId", "3"),
        new KeyValuePair<string, string>("flagValueToSet", "true")
      });

      // response.Result.IsSuccessStatusCode == true and no errors
      var response = client.PostAsync($"{baseUri}/Deals/SetDealFlag?dealId=3&flagValueToSet=true", null); 

      // response.Result.IsSuccessStatusCode == false and 404 error
      // var response = client.PostAsync($"{baseUri}/Deals/SetDealFlag", content); 
      response.Wait();
      if (response.Result.IsSuccessStatusCode)
      {
        return;
      }
    }
    catch (Exception ex)
    {
      Console.WriteLine(ex.Message);
      throw;
    }
  }
}