.NET的HttpClient。如何发布字符串值? [英] .NET HttpClient. How to POST string value?

查看:121
本文介绍了.NET的HttpClient。如何发布字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建使用C#和HttpClient的以下POST请求:

我需要这样的请求,我的Web API服务:

  [ActionName(存在)]
[System.Web.Mvc.HttpPost]
公共BOOL CheckIfUserExist([FromBody]串登录)
{
    布尔结果= _membershipProvider.CheckIfExist(登录);
    返回结果;
}

在此先感谢!


解决方案

 使用系统;
使用System.Collections.Generic;
使用System.Net.Http;类节目
{
    静态无效的主要()
    {
        使用(VAR的客户=新的HttpClient())
        {
            client.BaseAddress =新的URI(HTTP://本地主机:6740);
            VAR内容=新FormUrlEn codedContent(新[]
            {
                新KeyValuePair<字符串,字符串>(,登录)
            });
            VAR的结果= client.PostAsync(/ API /会员/存在,内容)。结果;
            字符串resultContent = result.Content.ReadAsStringAsync()结果。
            Console.WriteLine(resultContent);
        }
    }
}

How can I create using C# and HttpClient the following POST request:

I need such request for my WEB API service:

[ActionName("exist")]
[System.Web.Mvc.HttpPost]
public bool CheckIfUserExist([FromBody] string login)
{           
    bool result = _membershipProvider.CheckIfExist(login);
    return result;
}

Thanks in advance!

解决方案

using System;
using System.Collections.Generic;
using System.Net.Http;

class Program
{
    static void Main()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:6740");
            var content = new FormUrlEncodedContent(new[] 
            {
                new KeyValuePair<string, string>("", "login")
            });
            var result = client.PostAsync("/api/Membership/exists", content).Result;
            string resultContent = result.Content.ReadAsStringAsync().Result;
            Console.WriteLine(resultContent);
        }
    }
}

这篇关于.NET的HttpClient。如何发布字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆