【问题标题】:HttpClient post request for WebApi using asp.net mvc application使用 asp.net mvc 应用程序对 WebApi 的 HttpClient 发布请求
【发布时间】:2016-08-25 07:47:31
【问题描述】:

我正在尝试使用 WebApi,但遇到了问题。我的“IsSuccessStatusCode”总是错误的,我有 404 作为回应。

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

常量:

const string baseUri = ""; // base url of API
const string setDealFlagUri = "Deals/SetDealFlag";

方法一,使用 PostAsync:

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;
    }
}

方法二,使用 PostAsJsonAsync:

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;
    }
}

WebApi 请求详情:

卷曲:

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

请求网址

{baseApiurl}/Deals/SetDealFlag?dealId=3&flagValueToSet=true

响应正文

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

响应标头

{
  "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"
}

请帮我正确使用这个webapi函数。 谢谢!

【问题讨论】:

  • 什么问题? IsSuccessStatusCode 总是 false?如果是这样,response 中的内容是什么?
  • 是的,“IsSuccessStatusCode”始终为假。我有 404 响应。
  • @Saadi 404 - 表示未找到。所以先检查你的网址
  • 网址对我来说似乎没问题。我还在我的问题中添加了我的 url 常量。你可以检查一下。好像还可以
  • @Saadi 我不完全确定,但我可以看到您通过 URL 发送数据,而不是作为表单(使用 cURL)。您是否尝试将您的请求发布到https://energydevdealswebservices20160719041846.azurewebsites.net/Deals/SetDealFlag?deadid=3&amp;flagValueToSet=true url,而不是将数据作为内容发送到https://energydevdealswebservices20160719041846.azurewebsites.net/Deals/SetDealFlag

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


【解决方案1】:

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

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

我说的对吗?如果您的回答是“是”,那么您的方法需要 URL 中的参数。

因此您会收到 404 错误,因为您的任何 Web API 方法都与该 URL 不匹配。

在 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;
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 2015-06-13
    • 2017-03-09
    • 1970-01-01
    • 2015-08-24
    • 2012-10-23
    • 1970-01-01
    相关资源
    最近更新 更多