C#通过HttpClient访问WebAPI,获取返回结果
程序员文章站
2024-02-20 10:59:28
...
HttpClient的使用方法有很多,不再赘述。
1.Web API
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet("requesttest")]
public IActionResult RequestTest()
{
return Ok("返回的信息");
}
}
2.Web APP
public class IndexModel : PageModel
{
private IHttpClientFactory _httpClientFactory;
public IndexModel(IHttpClientFactory httpClientFactory)//通过依赖注入方式,注意在startup类中注册 services.AddHttpClient();
{
_httpClientFactory = httpClientFactory;
}
public string Result { get; set; }
public async Task OnGetAsync()
{
var client = _httpClientFactory.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:5100/api/values/requesttest");
var respond = await client.SendAsync(request).Result.Content.ReadAsStringAsync();//
Result = respond;//显示
}
}
上一篇: shell脚本之石头剪刀布小游戏
下一篇: Shell脚本——石头剪刀布小游戏