Метод действия с вызовом JSON API выдает ошибку 500 - PullRequest
0 голосов
/ 17 декабря 2018

Я выполняю вызов API, который работает нормально на localhost, но когда я запускаю его на сервере, сначала страница запрашивает авторизацию (скриншот прилагается).Если я пропущу этот шаг, я получу следующую ошибку:

enter image description here

401 - Несанкционированный: доступ запрещен из-за неверных учетных данных.У вас нет разрешения на просмотр этого каталога или страницы с использованием предоставленных вами учетных данных.

Если я предоставляю учетные данные администратора сервера, я получаю следующее:

Ошибка конфигурации Описание:Произошла ошибка во время обработки файла конфигурации, необходимого для обслуживания этого запроса.Пожалуйста, просмотрите подробности конкретной ошибки ниже и измените файл конфигурации соответствующим образом.

Сообщение об ошибке синтаксического анализатора: при загрузке файла конфигурации произошла ошибка: не удалось запустить мониторинг изменений в «C: ... \ test», поскольку доступ запрещен.

Произошла ошибка приложения насервер.Текущие пользовательские настройки ошибок для этого приложения не позволяют удаленно просматривать подробности ошибки приложения (из соображений безопасности).Однако его могут просматривать браузеры, работающие на локальном сервере.

У меня уже установлено customErrors mode = "Off" в файле web.config сервера.

<system.web>
   ...
   <customErrors mode="Off" />
   ...
</system.web>

Нижемой код:

public ActionResult ApiTest{
   var baseUri = "https://<apiurl>/products";
   var json = "{\"requestList\": {\"access_id\": \"access_id\", \"access_key\": \"access_key\", \"clientIpAdr\": \"x.x.x.x\", \"currency\": \"USD\", \"lang\": \"en\", \"filters\": { \"product_category\": 1, \"reference_no\": \"xxxxxx\" } } }";
   var result = "";

   var request = (HttpWebRequest)WebRequest.Create(baseUri);
   request.ContentType = "application/json";
   request.Accept = "text/json";
   request.Method = "POST";
   request.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
   ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

   using (var sw = new StreamWriter(request.GetRequestStream()))
   {
       sw.Write(json);
       sw.Flush();
       sw.Close();
   }

   try
   {
       var response = (HttpWebResponse)request.GetResponse();
       using (var sr = new StreamReader(response.GetResponseStream()))
       {
           result = sr.ReadToEnd();
       }
   }

   catch (WebException webex)
   {
       WebResponse errResp = webex.Response;
       using (Stream respStream = errResp.GetResponseStream())
       {
           StreamReader reader = new StreamReader(respStream);
           result = reader.ReadToEnd();
       }
   }

   dynamic jsonObj = JsonConvert.DeserializeObject(result);
      var models = jsonObj.master;
   }

   ViewBag.Result = result;
   return View();
}

Я полностью облажался !!: (

РЕДАКТИРОВАТЬ:

Содержимое файла Web.config, используемого на сервере:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
    <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=xxx" requirePermission="false" />
        <!--<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />-->
        <section name="resizer" type="ImageResizer.ResizerSection" requirePermission="false" />
    </configSections>
    <connectionStrings>
        <add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\xxx.mdf;Initial Catalog=xxx;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
        <add name="xxx" connectionString="metadata=res://*/Models.xxx.csdl|res://*/Models.xxx.ssdl|res://*/Models.xxx.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=localhost;initial catalog=xxx;user id=xxx;password=xxx;TransparentNetworkIPResolution=False;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
        <add name="CLXLandingEntities" connectionString=".." providerName="System.Data.EntityClient" />
    </connectionStrings>
    <appSettings>
        <add key="webpages:Version" value="2.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="PreserveLoginUrl" value="true" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
        <!-- Custom entries -->
        <add key="CryptoKey" value="xxx" />
        <!-- Message Log Keys -->
        <add key="GeneralInquiry" value="abd010e9-f9fe-4e2b-bbc6-b8a3ece2f7a1" />
        <add key="ScheduledTestDrive" value="ddf52846-10bf-415c-a8ea-a44d313a11ad" />
        <add key="MakeAnOffer" value="6d27d834-5ce5-4ea7-b8b6-e38fe16fdba7" />
        <add key="BaseDomain" value="http://basedomain.com/" />

        <!-- Write below key in web.config file when implementing custom membersip. Otherwise, Godaddy would show SSE error-->
        <add key="enableSimpleMembership" value="false" />

        <add key="VehicleDescriptionPlaceholderText" value="Respond To This AD For Details" />

        <!-- Site mode-->
        <add key="SiteMode" value="L" />
        <add key="DevEmail" value="xxx@gmail.com" />

        <add key="ManualUploadDisplay" value="On"/>
        <!-- ImageOptim -->
        <add key="imageoptim_username" value="xxx"/>
        <add key="imageoptim_doc" value="https://imageoptim.com/api/get?username=xxx"/>

        <add key="exclude_vehicle_price_in_search" value="10" />

        <add key="public_warranty_sales_person_id" value="xxx"/>
        <add key="public_warranty_default_dealer_id" value="xxx"/>

        <add key="PhotoDefaultWatermark" value="xxx" />

        <!-- Canonical -->
        <add key="RenderCononical" value="YES" />

        <!-- Message Bird -->
        <add key="MessageBirdSubject" value="xxx" />

        <!-- Dealer / Seller / Reseller public page generic tagline-->
        <add key="TagLine" value="Cars for sale."/>

    </appSettings>
    <system.web>
        <caching>
            <outputCacheSettings>
                <outputCacheProfiles>
                    <add name="CacheCompressedContent10Minutes" duration="600"/>
                </outputCacheProfiles>
            </outputCacheSettings>
        </caching>
        <customErrors mode="Off" />
        <!-- Set session timeout to 1 hour (60 minutes) -->
        <sessionState timeout="60"></sessionState>
        <compilation debug="true" targetFramework="4.0">
            <assemblies>
                <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
            </assemblies>
        </compilation>
        <authentication mode="Forms">
            <forms loginUrl="~/login" timeout="2880" />
        </authentication>
        <pages  validateRequest="false">
            <namespaces>
                <add namespace="System.Web.Helpers" />
                <add namespace="System.Web.Mvc" />
                <add namespace="System.Web.Mvc.Ajax" />
                <add namespace="System.Web.Mvc.Html" />
                <add namespace="System.Web.Optimization" />
                <add namespace="System.Web.Routing" />
                <add namespace="System.Web.WebPages" />
            </namespaces>
        </pages>
        <!-- request length (1048 MB) -->
        <httpRuntime maxRequestLength="1048576"  requestPathInvalidCharacters="" requestValidationMode="2.0"/>
        <httpModules>
            <add name="ImageResizingModule" type="ImageResizer.InterceptModule" />
            <add name="ContentCompresser" type="MinifyContent.ContentCompresser, MinifyContent" />
        </httpModules>
    </system.web>
    <system.webServer>
        <urlCompression doStaticCompression="true" doDynamicCompression="true" />
        <staticContent>
            <clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
        </staticContent>
        <validation validateIntegratedModeConfiguration="false" />
        <modules runAllManagedModulesForAllRequests="true">
            <add name="ImageResizingModule" type="ImageResizer.InterceptModule" />
        </modules>
        <handlers>
            <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
            <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
            <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
            <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
            <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
            <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
            <!-- Another option to fix multiple words in URL for deale search. Will look inti it later -->
            <!--<add name="ApiURIs-ISAPI-Integrated-4.0" path="/search-dealers/*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />-->
        </handlers>
        <httpRedirect enabled="false" destination="http://example.com/" exactDestination="false" httpResponseStatus="Found" />
        <security>
            <!--
                Resource: /5780646/dvoinaya-posledovatelnost-filtratsii-zaprosov-nastroen-otklonenie-zaprosa-kotoryi-soderzhit-dvoinuy-posledovatelnost
                Resource: http://stackoverflow.com/questions/1453218/is-enabling-double-escaping-dangerous
            -->
            <requestFiltering allowDoubleEscaping="true">
                <requestLimits maxAllowedContentLength="1073741824" />
            </requestFiltering>
        </security>
        <!--redirect to https -->
        <rewrite>
            <rules>
                <rule name="HTTP to HTTPS redirect" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    </conditions>
                    <action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}/{R:1}" />
                </rule>
            </rules>
        </rewrite>
        <!--redirect to https-->
    </system.webServer>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" />
                <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" />
                <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
            </dependentAssembly>
            <dependentAssembly>
                <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
                <bindingRedirect oldVersion="0.0.0.0-1.3.0.0" newVersion="1.3.0.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
    <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    </entityFramework>
    <resizer>
        <plugins>
            <add name="MvcRoutingShim" />
            <add name="SimpleFilters" />
        </plugins>
    </resizer>

</configuration>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...