加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

在ASP.NET 5中使用WebClient

发布时间:2020-12-16 03:42:34 所属栏目:asp.Net 来源:网络整理
导读:我正在使用VS15测试版并尝试使用WebClient.虽然引用了System.Net,并且intellisense建议WebClient类可用,但在构建时我收到以下错误: The type or namespace name ‘WebClient’ does not exist in the namespace ‘System.Net’ (are you missing an assembl
我正在使用VS15测试版并尝试使用WebClient.虽然引用了System.Net,并且intellisense建议WebClient类可用,但在构建时我收到以下错误:

The type or namespace name ‘WebClient’ does not exist in the namespace ‘System.Net’ (are you missing an assembly reference?) MyProj.ASP.NET Core 5.0 HomeController.cs

我正在做以下简单的代码:

var client = new System.Net.
var html = client.DownloadString(url);

当我转到Web客户端的定义时,它向我展示了源代码.不太确定问题是什么 – WebClient移动了吗?我正在努力寻找解决方案.

谢谢!

解决方法

不确定WebClient,但您也可以使用System.Net.Http.HttpClient来发出Web请求.

将这些引用添加到project.json:

"frameworks": {
    "aspnet50": {
        "frameworkAssemblies": {
            "System.Net.Http": "4.0.0.0"
        }
    },"aspnetcore50": {
        "dependencies": {
            "System.Net.Http": "4.0.0-beta-*"
        }
    }
},

接下来是如何从MVC 6动作方法调用它:

using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;

namespace WebApplication50.Controllers
{
    public class HomeController : Controller
    {
        public async Task<IActionResult> Index()
        {
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MyClient","1.0"));
            var result = await httpClient.GetStringAsync("http://www.microsoft.com");

            ...

            return View();
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读