繁体   English   中英

使用参数C#发布WebApi方法

[英]Post WebApi Method With Parameter C#

我只想在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,因此您可以看到可能存在问题的地方。

考虑使用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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM