从控制台访问控制器

时间:2019-08-21 15:21:50

标签: asp.net-mvc httpwebrequest

我有一个MVC Web项目,该项目具有一个API控制器,我想从控制台应用程序发送数据。我收到错误System.Net.WebException:“远程服务器返回错误:(401)未经授权。”但是我发送了我知道可以访问该网站的用户名和密码。

  

这可以做吗?我应该调用FormsAuthentication控制器吗?

MVC项目控制器

 [ApplicationApiAuthorize("Administrator, ContentManager")]
        public IHttpActionResult RegenerateExportData([FromBody] string[] versionKeys)

控制台应用程序

     public static string CallRestMethod(string url,string USERNAME, string PASSWORD)
        {
            string versionKey = "ode5mg";

            HttpWebRequest HttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            HttpWebRequest.Method = "POST";

            byte[] data = Encoding.ASCII.GetBytes(versionKey);

            var cache = new CredentialCache();
            cache.Add(new Uri(url), "Digest", new NetworkCredential(USERNAME, PASSWORD));
            HttpWebRequest.Credentials = cache;
            HttpWebRequest.PreAuthenticate = true;
            //HttpWebRequest.Credentials = new NetworkCredential(USERNAME, PASSWORD);


            HttpWebRequest.ContentType = "application/x-www-form-urlencoded";
            HttpWebRequest.ContentLength = data.Length;

            Stream requestStream = HttpWebRequest.GetRequestStream();
            requestStream.Write(data, 0, data.Length);
            requestStream.Close();

            HttpWebResponse myHttpWebResponse = (HttpWebResponse)HttpWebRequest.GetResponse();
}

IIS日志我看不到有关子代码0的任何内容

2019-08-21 15:37:56 172.16.2.108 POST /Api/TemplatesManagement/RegenerateExportData - 80 - 172.16.6.97 - - 401 0 0 12259

0 个答案:

没有答案