使用参数C#发布WebApi方法

时间:2017-11-01 14:01:26

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

我想在asp.net mvc中发布Webapi方法,post action方法看起来像

  [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页面。 请帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

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