代码之家  ›  专栏  ›  技术社区  ›  JSBach

如何使用WebClient类将值从一台服务器发布到另一台服务器?

  •  0
  • JSBach  · 技术社区  · 11 年前

    我正在尝试使用WebAPI技术将请求从一台服务器发布到另一台服务器。 这是我接收调用的方法

    [HttpGet]
        [HttpPost]
        public HttpResponseMessage MyMethod([FromBody] string token, [FromBody] string email, [FromBody] string password)
        {
    
            string a = "hello world!";
            return new HttpResponseMessage() { Content = new StringContent(a) };
        }
    

    我正在使用此代码贴:

    using (var c = new WebClient())
            {
                //string obj = ":" + JsonConvert.SerializeObject(new { token= "token", email="email", password="password" });
                NameValueCollection myNameValueCollection = new NameValueCollection();
    
                // Add necessary parameter/value pairs to the name/value container.
                myNameValueCollection.Add("token", "token");
                myNameValueCollection.Add("email", "email");
    
                myNameValueCollection.Add("password", "password");
    
                byte[] responseArray = c.UploadValues("MyServer/MyMethod", "POST", myNameValueCollection);
    
    
                return Encoding.ASCII.GetString(responseArray);
            }
    

    我已经尝试了几种替代方案。

    我上面写的这个给了我一个内部服务器错误,MyMethod中的断点没有命中,所以问题不在我的方法代码上。

    在注释为我的nameValueCollection添加参数的三行时,我得到了404。

    从MyMethod的签名中删除参数,它就起作用了。

    我想将这些信息发布到我的服务器上,该服务器承载API。

    你知道我做错了什么吗?

    1 回复  |  直到 11 年前
        1
  •  1
  •   Darin Dimitrov    11 年前

    一如既往,从编写视图模型开始:

    public class MyViewModel 
    {
        public string Token { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
    }
    

    您的控制器操作将作为参数:

    [HttpPost]
    public HttpResponseMessage MyMethod(MyViewModel model)
    {
    
        string a = "hello world!";
        return new HttpResponseMessage() { Content = new StringContent(a) };
    }
    

    注意,我已经摆脱了 [HttpGet] 属性你必须选择动词。顺便说一句,如果你遵循标准的ASP.NET Web API路由约定,你的操作的名称应该与用来访问它的HTTP谓词相对应。这是标准的RESTful约定。

    现在您可以点击:

    using (var c = new WebClient())
    {
        var myNameValueCollection = new NameValueCollection();
    
            // Add necessary parameter/value pairs to the name/value container.
        myNameValueCollection.Add("token", "token");
        myNameValueCollection.Add("email", "email");
        myNameValueCollection.Add("password", "password");
    
        byte[] responseArray = c.UploadValues("MyServer/MyMethod", "POST", myNameValueCollection);
    
        return Encoding.ASCII.GetString(responseArray);
    }