【问题标题】:Post WebApi Method With Parameter C#使用参数 C# 发布 WebApi 方法
【发布时间】:2017-11-01 14:01:25
【问题描述】:

我只想在 asp.net mvc 中发布 Webapi 方法,发布操作方法看起来像

  [HttpPost]
    [Route("api/agency/Dashboard")]
    public HttpResponseMessage Index(getCookiesModel cookies)
    {
     //code here
    }

我正在发送这样的帖子请求

  string result = webClient.DownloadString("http://localhost:11668/api/agency/dashboard?cookies=" + cookies);

和 getCookiesModel

 public class getCookiesModel
{
    public string userToken { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public long userId { get; set; }
    public string username { get; set; }
    public string country { get; set; }
    public string usercode { get; set; }
}

但是找不到这个返回 404 页面。 请帮我解决这个问题。

【问题讨论】:

  • DownloadString 是一个 GET 请求,由于该操作需要一个 POST,因此您可以看到问题所在。
  • 请问如何解决。
  • 呃...从 Post 更改为 Get?
  • @DumpsterDiver:删除 [HttpPost] 注释,以便可以从 GET 请求中使用该操作。

标签: c# asp.net-web-api routing


【解决方案1】:

DownloadString 是一个 GET 请求,由于该操作需要一个 POST,因此您可以看到问题所在。

考虑使用HttpClient 发布请求。如果在正文中发送有效负载,则不需要查询字符串,因此您还需要更新客户端调用 URL。

var client = new HttpCient { 
    BaseUri = new Uri("http://localhost:11668/")
};

var model = new getCookiesModel() {
    //...populate properties.
};
var url = "api/agency/dashboard";
//send POST request
var response = await client.PostAsJsonAsync(url, model);
//read the content of the response as a string
var responseString = await response.Content.ReadAsStringAsync();

Web API 应遵循以下语法

[HttpPost]
[Route("api/agency/Dashboard")]
public IHttpActionResult Index([FromBody]getCookiesModel cookies) {
    //code here...
    return Ok();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    相关资源
    最近更新 更多