.Net Core能调用普通WebService吗?答案是肯定的


.Net Core能调用普通WebService吗?答案是肯定的


.net core2.2版本,微软提供了访问第三方服务的扩展,只需要在Startup.cs中添加。

.Net Core能调用普通WebService吗?答案是肯定的

紧接着就是通过DI直接使用。示例如下:

<code>using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace demo.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;

public ValuesController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}

[HttpGet]
public async Task<actionresult>> Get()
{
var url = @"http://127.0.0.1:8888/demo/test.asmx/save";

Dictionary<string> dicParam = new Dictionary<string>();
dicParam.Add("id", "1");
dicParam.Add("name", "张三");
HttpContent content = new FormUrlEncodedContent(dicParam);

return await RemoteHelper(url, content);
}

private async Task<string> RemoteHelper(string url, HttpContent content)
{
var result = string.Empty;
try
{
using (var client = _httpClientFactory.CreateClient())
using (var response = await client.PostAsync(url, content))
{
if (response.StatusCode == HttpStatusCode.OK)
{
result = await response.Content.ReadAsStringAsync();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return result;
}
}
}/<string>/<string>/<string>/<actionresult>/<code>


.Net Core能调用普通WebService吗?答案是肯定的


分享到:


相關文章: