Using WebClient in ASP.NET 5

∥☆過路亽.° 提交于 2019-12-12 11:09:36

问题


I am working in the VS15 beta and trying to use WebClient. While System.Net is referenced, and the intellisense suggests the WebClient class is available, on build I get the following error:

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

I am doing the following simplistic code:

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

When I go to the definition of Web Client, it shows me the source. Not quite sure what the issue is - is WebClient moved? I am struggling to find the resolution.

Thanks!


回答1:


Not sure about WebClient, but you can use System.Net.Http.HttpClient to make web requests as well.

Add these references to the project.json:

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

And then here's how to call it from an MVC 6 action method:

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();
        }
    }
}



回答2:


You can still use WebClient if you only target full .NET Framework instead of .NET Core by in your project.json changing:

  "frameworks": {
    "dnx451": { },
    "dnxcore50": { }
  },

to

  "frameworks": {
    "dnx451": { }
  },


来源:https://stackoverflow.com/questions/26958966/using-webclient-in-asp-net-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!