Меню

System net webexception удаленный сервер возвратил ошибку 401 несанкционированный

  • Remove From My Forums
  • Question

  • User-649116597 posted

    When I run my web application. I got this error!!!!!!

    Line 133:            request.Method = "GET";
    Line 134:
    Line 135: using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) Line 136:            {
    Line 137:                StreamReader reader = new StreamReader(response.GetResponseStream());

    Source File: C:UsersAnuragDocumentsVisual Studio 2010ProjectsTicketSystemTicketSystemDefault.aspx.cs    Line:
    135

    Stack Trace:

    [WebException: The remote server returned an error: (401) Unauthorized.]
       System.Net.HttpWebRequest.GetResponse() +6111075
       TicketSystem._Default.Button2_Click(Object sender, EventArgs e) in C:UsersAnuragDocumentsVisual Studio 2010ProjectsTicketSystemTicketSystemDefault.aspx.cs:135
       System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
       System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
       System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
       System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
       System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
    

Answers

  • User-650628323 posted

    Hi,

    I agree with BrockAllen’s opinion. According to your description, you need to add the add Credentials for HttpWebRequest.  

    // Assign the credentials of the logged in user or the user being impersonated.
    request.Credentials = CredentialCache.DefaultCredentials;
    

    Or

    request.Credentials = new NetworkCredential("UserName", "PassWord"); 

    For details about it, please
    NetworkCredential Class and
    CredentialCache.DefaultCredentials Property.

    Best wishes,

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

BaLahmuT

85 / 29 / 16

Регистрация: 01.06.2019

Сообщений: 608

1

14.04.2021, 22:01. Показов 8643. Ответов 8

Метки нет (Все метки)


Получаю погоду с api, при запуске представления вылетает ошибка: System.Net.WebException: «Удаленный сервер возвратил ошибку: (401) Несанкционированный.»

Модель:

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 public class Weather
    {
        public Object getWeather()
        {
            string url = "http://api.openweathermap.org/data/2.5/weather?q=Kharkiv&APPID=03e45b7211028e0119ce0b1b3fa9fa90units=imperial";
 
            var client = new WebClient();
            var content = client.DownloadString(url);
 
            var serializer = new JavaScriptSerializer();
            var jsonContent = serializer.Deserialize<Object>(content);
 
            return jsonContent;
        }
    }

Контроллер:

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
 
        public ActionResult Api()
        {
            return View();
        }
 
        public ActionResult Weather()
        {
            return View();
        }
 
        public JsonResult GetWeather()
        {
            Weather weath = new Weather();
            return Json(weath.getWeather(), JsonRequestBehavior.AllowGet);
        }
    }

Представление:

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@{ 
    ViewBag.Title = "Weather"; 
}
 
<h2>Weather</h2>
<div class="col-md-12">
    <h1>Current Conditions in <span data-bind="text:name"></span></h1>
</div>
 
<div class="col-md-12">
    Temperature is <span data-bind="text:main.temp"></span>&deg; F
</div>
 
<script>
    var weather = Object();
    $(document).ready(function () {
            $.get("@Url.Action("GetWeather", "Home")", function (response) {
                console.log(response);
                weather = ko.mapping.fromJS(response);
                ko.applyBindings(weather);
 
            });
    });
 
</script>

Миниатюры

Ошибка "(401) Несанкционированный"
 

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



647 / 582 / 170

Регистрация: 17.07.2012

Сообщений: 1,648

Записей в блоге: 1

14.04.2021, 23:25

2

Rudman132, 401 отдает API. Видимо ему ключ какой-то нужен.



1



BaLahmuT

85 / 29 / 16

Регистрация: 01.06.2019

Сообщений: 608

15.04.2021, 15:13

 [ТС]

3

Cupko, Хмм..странно, если api ключ вынести в отдельную переменную то все работает

C#
1
string url = "http://api.openweathermap.org/data/2.5/weather?q=Cairo&APPID=" + key + "&units=imperial";



0



922 / 600 / 149

Регистрация: 09.09.2011

Сообщений: 1,879

Записей в блоге: 2

15.04.2021, 18:47

4

Лучший ответ Сообщение было отмечено Rudman132 как решение

Решение

Цитата
Сообщение от Rudman132
Посмотреть сообщение

странно, если api ключ вынести в отдельную переменную то все работает

Ничего странного. Пропущен разделитель.
&APPID=03e45b7211028e0119ce0b1b3fa9fa90<-тут-->units=imperial
Так что и первый вариант бы работал
Но второй правильнее с точки зрения программирования. Вы ж ключ менять будете и не раз. Не в тексте же его менять.



1



BaLahmuT

85 / 29 / 16

Регистрация: 01.06.2019

Сообщений: 608

15.04.2021, 23:09

 [ТС]

5

Вопрос такой, как привязать форму к api? чтоб город можно было указывать любой

C#
1
string url = "http://api.openweathermap.org/data/2.5/weather?q=Cairo&APPID=" + key + "&units=imperial";

Вот форма:

Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
form action="Index" method="post" style="text-align: center">
        <table>
            <tr>
                <td style="font-size:18px">Enter city:</td>
                <td>
                    <input type="text" name="city" />
                    <input type="submit" id="search" value="Search"/>
                </td>
            </tr>
        </table>
        <hr />
    </form>



0



922 / 600 / 149

Регистрация: 09.09.2011

Сообщений: 1,879

Записей в блоге: 2

16.04.2021, 23:14

6

Цитата
Сообщение от Rudman132
Посмотреть сообщение

Вопрос такой, как привязать форму к api? чтоб город можно было указывать любой

Я давно не работал с погодным апи. Но наверное это с ним и не должно быть связано.
Объясните причину вопроса? Что такое привязать форму к АПИ? Или так — Зачем нужно привязать что-то к форме?

Форма — ввод города. Всё. Роль на этом заканчивается.
Запрос вы отправляете через бакэнд. Там вы и подставляете ключ. Собственно на бакэнде вы и можете манипулировать данными так как вам нужно.
И поэтому не понятно что за проблема вообще «можно было указывать любой город»



0



BaLahmuT

85 / 29 / 16

Регистрация: 01.06.2019

Сообщений: 608

17.04.2021, 11:04

 [ТС]

7

HF, Может неправильно сформулировал, имел ввиду: как текст из inputa подставить вместо

C#
1
q=Cairo



0



922 / 600 / 149

Регистрация: 09.09.2011

Сообщений: 1,879

Записей в блоге: 2

17.04.2021, 22:12

8

Лучший ответ Сообщение было отмечено Rudman132 как решение

Решение

Цитата
Сообщение от Rudman132
Посмотреть сообщение

Может неправильно сформулировал, имел ввиду: как текст из inputa подставить вместо

Судя по представлению — у вас запрос сразу уходит. Значит
1) вы должны сделать событие onclick на кнопку формы
2) и отправлять запрос исходя из данных этой формы. А точнее поля City
Далее запрос. Сейчас он у вас вызывает голый метод. А вы же хотите город. Значит и должны город передавать.
3) обновляйте запрос $.get("@Url.Action("GetWeather", "Home")" и добавляйте аргументом поле «city» из формы
Соответственно и контроллер должен начать принимать это поле
4) добавляйте в метод контроллера параметр string city
5) ваша переменная uri теперь должна подставлять значение city в ключ «q» аналогично ключу авторизации.



0



85 / 29 / 16

Регистрация: 01.06.2019

Сообщений: 608

17.04.2021, 23:17

 [ТС]

9

HF, понял, спасибо!



0



  • Remove From My Forums
  • Вопрос

  • Коллеги, добрый день!

    Из сети интернет и в локальной сети при обращение к адресу https://mail.domain.ru/autodiscover/autodiscover.xml выходит запрос авторизации и не пускает в каталог.

    Настройки IIS

    Как правильно настроить чтобы отрабатывал https://mail.domain.ru/autodiscover/autodiscover.xml ?

Ответы

  • По поводу предупреждения EventId 6037 от источника LSA (LsaSrv): у вас отсутствует SPN HOST/mail.замазано.su, нужный для аутентификации по Kerberos при обращении к Exchange. Данная ошибка зафиксирована службой мониторинга (судя по имени
    exe), но она же может препятствовать доступу как раз клиентов из домена.

    Как я понимаю, у вас либо сервер называется не mail, либо домен AD у вас — не mail.что-то-там.su.  Если ни то, ни другое неверно, то, значит, кто-то кривыми руками SPN поправил.

    В любом случае, проверьте отсутсвие имени:

    setspn -Q HOST/mail.замазано.su

    Если его нет — добавьте:

    setpn -S HOST/mail.замазано.su NetBIOS-имя-сервера


    Слава России!

    • Изменено

      14 апреля 2020 г. 15:31

    • Помечено в качестве ответа
      Vasilev VasilMicrosoft contingent staff
      27 апреля 2020 г. 8:42

    • Изменено
      M.V.V. _
      14 апреля 2020 г. 19:18
    • Помечено в качестве ответа
      Vasilev VasilMicrosoft contingent staff
      27 апреля 2020 г. 8:42

#c# #asp.net #asp.net-web-api #sharepoint

Вопрос:

Я пытаюсь загрузить лист Excel из общей точки на мой путь к локальной машине.

Вот что я попробовал:

 public class ReadAndDownloadController : ApiController
{
    public string Get()
    {           
        const string username = "**********";
        const string password = "**********";            
        const string url = "https://globalfunctionsshare.nam.citi.net/sites/otdrrm/_layouts/15/WopiFrame.aspx?sourcedoc=/sites/otdrrm/Documents/tools/Legal Hold Application Tracker/Legal Hold Application Tracker 20210702.xlsx";
        var securedPassword = new SecureString();
        foreach (var c in password.ToCharArray()) securedPassword.AppendChar(c);
        var credentials = new SharePointOnlineCredentials(username, securedPassword);

        DownloadFile(url, credentials, @"C:ImpDocstemp.xslx");

        return "XYZ";
    }              

    private static void DownloadFile(string webUrl, ICredentials credentials, string fileRelativeUrl)
    {
        using (var client = new WebClient())
        {
            client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            client.Headers.Add("User-Agent: Other");
            client.Credentials = credentials;
            client.DownloadFile(webUrl, fileRelativeUrl); ----> Here I'm getting Error
        }
    }
}
 

Но когда я пытаюсь запустить этот код, я получаю ошибку, как

«Исключение типа» System.Net.WebException » произошло в System.dll но не был обработан в пользовательском коде

Дополнительная информация: Удаленный сервер вернул сообщение об ошибке: (401) Несанкционированное.»

Я не понимаю, в чем здесь собственно проблема. URL-адрес точки обмена верен, мои учетные данные верны, также существует путь, по которому я загружаю.

Это стоило мне целого дня. Пожалуйста, если кто-нибудь может помочь, это будет большая помощь

Комментарии:

1. Есть ли какой — либо другой способ проверить ваши учетные данные? Например, можете ли вы попробовать войти в систему вручную с помощью известного хорошего инструмента? Или вы можете проверить журналы сервера, чтобы узнать причину 401?

2. Мы не рекомендуем вам использовать WebClient класс для новой разработки. Вместо этого используйте System.Net.Http.HttpClient класс.

3. @aepot : У вас есть какой-либо исходный код с HttpClient, потому что у меня было немного знаний о WebClient. Пожалуйста, если вы можете помочь мне с примером или ссылкой с помощью HttpClient

4. Вы можете легко найти здесь сотни примеров. Это очень популярный класс.

5. Вы можете начать обучение здесь и здесь .

  • Remove From My Forums
  • Question

  • User1760698851 posted

    I have WEB API & Web application both running on same server. I have enabled both for windows authentication. Web Application is consuming WEB API

    code :

    public static List<Course> GetCourses()
    
    {
    
        List<Course> courseList = new List<Course>();
        webClient.Credentials = new NetworkCredential("xxx", "yyy","UAT");
        string courses = webClient.DownloadString("http://xx.yy.zz/api/Courses");
    
        dynamic dynObj = JsonConvert.DeserializeObject(courses);
            foreach (var data in dynObj)
               {
                   Course course = new Course((string)data.CourseId, (string)data.CourseCode, (string)data.Description, (string)data.Name, (string)data.TypeCode);
                   courseList.Add(course);
               }
         return Course.SortCoursesAlpha(courseList);
    
    }

    This works  locally when I tried to debug from my local machine where it works without popping username & password

    . But after publishing to a server and when I tried to see if it works . It pops up the username & password and gives me :

    Server Error in ‘/’ Application.


    The remote server returned an error: (401) Unauthorized.

    Description: An
    unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

    Exception Details: System.Net.WebException: The remote server returned an error: (401) Unauthorized.

    Source Error:

    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.


    Stack Trace: 

    [WebException: The remote server returned an error: (401) Unauthorized.]
       System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) +283
       System.Net.WebClient.DownloadString(Uri address) +100
       System.Net.WebClient.DownloadString(String address) +29
       StudentMailer.Mailer.ApiHandler.GetCourses() in c:StudentMailertrunkStudentMailerStudentMailerMailerApiHandler.cs:42
       StudentMailer._Default.Page_Load(Object sender, EventArgs e) in c:StudentMailertrunkStudentMailerStudentMailerDefault.aspx.cs:30
       System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
       System.Web.UI.Control.OnLoad(EventArgs e) +92
       System.Web.UI.Control.LoadRecursive() +54
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
    

    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34280

    web application application pool details :

    application pool : v4.0  Integrated LocalSystem  

Answers

  • User-2057865890 posted

    Hi Jim,

    You could create a registry key on the machine that is trying to access the server, and white list the domain you are trying to hit.

    • Click Start, click Run, type regedit, and then click OK.
    • In Registry Editor, locate and then click the following registry key: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlLsaMSV1_0
    • Right-click MSV1_0, point to New, and then click Multi-String Value.
    • Type BackConnectionHostNames, and then press ENTER.
    • Right-click BackConnectionHostNames, and then click Modify.
    • In the Value data box, type the host name or the host names for the sites that are on the local computer, and then click OK.
    • Quit Registry Editor, and then restart the IISAdmin service.

    reference: https://support.microsoft.com/en-us/kb/896861 

    Best Regards,

    Chris

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

  • User1760698851 posted

    Hi Chris,

    Thanks for all your effort  you made . Finally, it is working :

    It was not straight forward :

    On  the Server , I wasn’t able to access the WEB API & ASP.NET WEB application which was using WEB API to populate the data locally . ( Was helpfull to test locally on server)

    step 1 :

    You could create a registry key on the machine that is trying to access the server, and white list the domain you are trying to hit.

    • Click Start, click Run, type regedit, and then click OK.
    • In Registry Editor, locate and then click the following registry key: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlLsaMSV1_0
    • Right-click MSV1_0, point to New, and then click Multi-String Value.
    • Type BackConnectionHostNames, and then press ENTER.
    • Right-click BackConnectionHostNames, and then click Modify.
    • In the Value data box, type the host name or the host names for the sites that are on the local computer, and then click OK.
    • Quit Registry Editor, and then restart the IISAdmin service.

    reference: https://support.microsoft.com/en-us/kb/896861 

    Step 2: Install windows Authentication on IIS  &  Windows Authentication ( under IIS -> Authentication )  on both WEB API & ASP.NET web application

    Step 3: 

    My final code was ( if you are accessing WEB API & web application from same machine using windows authentication ) from a web application .

    private static  WebClient wc = new WebClient();
    
    
    public static List<Course> GetCourses()
    
    {
    
        List<Course> courseList = new List<Course>();
         wc.UseDefaultCredentials = true;
        string courses = webClient.DownloadString("http://xx.yy.zz/api/Courses");
        dynamic dynObj = JsonConvert.DeserializeObject(courses);
            foreach (var data in dynObj)
               {
                   Course course = new Course((string)data.CourseId, (string)data.CourseCode, (string)data.Description, (string)data.Name, (string)data.TypeCode);
                   courseList.Add(course);
               }
         return Course.SortCoursesAlpha(courseList);
    
    }
    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

  • Remove From My Forums
  • Question

  • User1760698851 posted

    I have WEB API & Web application both running on same server. I have enabled both for windows authentication. Web Application is consuming WEB API

    code :

    public static List<Course> GetCourses()
    
    {
    
        List<Course> courseList = new List<Course>();
        webClient.Credentials = new NetworkCredential("xxx", "yyy","UAT");
        string courses = webClient.DownloadString("http://xx.yy.zz/api/Courses");
    
        dynamic dynObj = JsonConvert.DeserializeObject(courses);
            foreach (var data in dynObj)
               {
                   Course course = new Course((string)data.CourseId, (string)data.CourseCode, (string)data.Description, (string)data.Name, (string)data.TypeCode);
                   courseList.Add(course);
               }
         return Course.SortCoursesAlpha(courseList);
    
    }

    This works  locally when I tried to debug from my local machine where it works without popping username & password

    . But after publishing to a server and when I tried to see if it works . It pops up the username & password and gives me :

    Server Error in ‘/’ Application.


    The remote server returned an error: (401) Unauthorized.

    Description: An
    unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

    Exception Details: System.Net.WebException: The remote server returned an error: (401) Unauthorized.

    Source Error:

    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.


    Stack Trace: 

    [WebException: The remote server returned an error: (401) Unauthorized.]
       System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) +283
       System.Net.WebClient.DownloadString(Uri address) +100
       System.Net.WebClient.DownloadString(String address) +29
       StudentMailer.Mailer.ApiHandler.GetCourses() in c:StudentMailertrunkStudentMailerStudentMailerMailerApiHandler.cs:42
       StudentMailer._Default.Page_Load(Object sender, EventArgs e) in c:StudentMailertrunkStudentMailerStudentMailerDefault.aspx.cs:30
       System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
       System.Web.UI.Control.OnLoad(EventArgs e) +92
       System.Web.UI.Control.LoadRecursive() +54
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
    

    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34280

    web application application pool details :

    application pool : v4.0  Integrated LocalSystem  

Answers

  • User-2057865890 posted

    Hi Jim,

    You could create a registry key on the machine that is trying to access the server, and white list the domain you are trying to hit.

    • Click Start, click Run, type regedit, and then click OK.
    • In Registry Editor, locate and then click the following registry key: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlLsaMSV1_0
    • Right-click MSV1_0, point to New, and then click Multi-String Value.
    • Type BackConnectionHostNames, and then press ENTER.
    • Right-click BackConnectionHostNames, and then click Modify.
    • In the Value data box, type the host name or the host names for the sites that are on the local computer, and then click OK.
    • Quit Registry Editor, and then restart the IISAdmin service.

    reference: https://support.microsoft.com/en-us/kb/896861 

    Best Regards,

    Chris

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

  • User1760698851 posted

    Hi Chris,

    Thanks for all your effort  you made . Finally, it is working :

    It was not straight forward :

    On  the Server , I wasn’t able to access the WEB API & ASP.NET WEB application which was using WEB API to populate the data locally . ( Was helpfull to test locally on server)

    step 1 :

    You could create a registry key on the machine that is trying to access the server, and white list the domain you are trying to hit.

    • Click Start, click Run, type regedit, and then click OK.
    • In Registry Editor, locate and then click the following registry key: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlLsaMSV1_0
    • Right-click MSV1_0, point to New, and then click Multi-String Value.
    • Type BackConnectionHostNames, and then press ENTER.
    • Right-click BackConnectionHostNames, and then click Modify.
    • In the Value data box, type the host name or the host names for the sites that are on the local computer, and then click OK.
    • Quit Registry Editor, and then restart the IISAdmin service.

    reference: https://support.microsoft.com/en-us/kb/896861 

    Step 2: Install windows Authentication on IIS  &  Windows Authentication ( under IIS -> Authentication )  on both WEB API & ASP.NET web application

    Step 3: 

    My final code was ( if you are accessing WEB API & web application from same machine using windows authentication ) from a web application .

    private static  WebClient wc = new WebClient();
    
    
    public static List<Course> GetCourses()
    
    {
    
        List<Course> courseList = new List<Course>();
         wc.UseDefaultCredentials = true;
        string courses = webClient.DownloadString("http://xx.yy.zz/api/Courses");
        dynamic dynObj = JsonConvert.DeserializeObject(courses);
            foreach (var data in dynObj)
               {
                   Course course = new Course((string)data.CourseId, (string)data.CourseCode, (string)data.Description, (string)data.Name, (string)data.TypeCode);
                   courseList.Add(course);
               }
         return Course.SortCoursesAlpha(courseList);
    
    }
    • Marked as answer by
      Anonymous
      Thursday, October 7, 2021 12:00 AM

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • System thread exception not handled windows 10 как исправить ошибку
  • System net webexception базовое соединение закрыто непредвиденная ошибка при передаче