- 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:
135Stack 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
-
Marked as answer by
|
BaLahmuT 85 / 29 / 16 Регистрация: 01.06.2019 Сообщений: 608 |
||||||||||||
|
1 |
||||||||||||
|
14.04.2021, 22:01. Показов 8643. Ответов 8 Метки нет (Все метки)
Получаю погоду с api, при запуске представления вылетает ошибка: System.Net.WebException: «Удаленный сервер возвратил ошибку: (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 ключ вынести в отдельную переменную то все работает
0 |
|
922 / 600 / 149 Регистрация: 09.09.2011 Сообщений: 1,879 Записей в блоге: 2 |
|
|
15.04.2021, 18:47 |
4 |
|
Решение
странно, если api ключ вынести в отдельную переменную то все работает Ничего странного. Пропущен разделитель.
1 |
|
BaLahmuT 85 / 29 / 16 Регистрация: 01.06.2019 Сообщений: 608 |
||||||||
|
15.04.2021, 23:09 [ТС] |
5 |
|||||||
|
Вопрос такой, как привязать форму к api? чтоб город можно было указывать любой
Вот форма: Кликните здесь для просмотра всего текста
0 |
|
922 / 600 / 149 Регистрация: 09.09.2011 Сообщений: 1,879 Записей в блоге: 2 |
|
|
16.04.2021, 23:14 |
6 |
|
Вопрос такой, как привязать форму к api? чтоб город можно было указывать любой Я давно не работал с погодным апи. Но наверное это с ним и не должно быть связано. Форма — ввод города. Всё. Роль на этом заканчивается.
0 |
|
BaLahmuT 85 / 29 / 16 Регистрация: 01.06.2019 Сообщений: 608 |
||||
|
17.04.2021, 11:04 [ТС] |
7 |
|||
|
HF, Может неправильно сформулировал, имел ввиду: как текст из inputa подставить вместо
0 |
|
922 / 600 / 149 Регистрация: 09.09.2011 Сообщений: 1,879 Записей в блоге: 2 |
|
|
17.04.2021, 22:12 |
8 |
|
Решение
Может неправильно сформулировал, имел ввиду: как текст из inputa подставить вместо Судя по представлению — у вас запрос сразу уходит. Значит
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
Сообщение было отмечено Rudman132 как решение
