Получение 404 на другой машине, почему? - PullRequest
0 голосов
/ 09 июля 2020

Я разрабатываю Asp. Net Core 3.1 API. Все работает нормально на моей машине, а также на машине другого разработчика, когда мы запускаем API локально из Visual Studio. Мы можем выполнить запрос и получить правильный ответ.

Но другой разработчик просто клонировал репо и получил последний код, используя git pull. Итак, у него тот же исходный код.

Когда он запускает проект локально из визуальной студии и пытается получить доступ к методам HTTP GET, он получает ошибку HTTP 404.

Он способный вызывать методы одного контроллера, а для методов HTTP GET другого контроллера он получает ошибку 404. и URL действителен.

Я также добавил AllowAnonymous на контроллере, в консоли браузера нет другой информации, кроме ошибки 404.

Так в чем может быть проблема?

Обновление:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using FxBatchProcCommon.Logger;
using FxBatchProcessing.InstructionValidation.Interfaces;
using FxBatchProcessing.InstructionValidation.Rules;
using FxBatchProcessing.Payment.Interfaces;
using FxBatchProcessing.Payment.Xml;
using FxBatchProcessing.Repository;
using ISOXMLValidationApi.Repositories;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;

namespace ISOXMLValidationApi
{
    public class Startup
    {
        private const string _apiVersion = "v1";

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddScoped<IISOXMLValidationRepository, ISOXMLValidationRepository>();
            services.AddScoped<IDBUtilRepository, DBUtilRepository>();
            services.AddScoped<IRuleManager, RuleManager>();
            services.AddScoped<IFieldRepository, FieldRepository>();
            services.AddScoped<IErrorRepository, ErrorRepository>();
            services.AddScoped<IBatchProcessorConfigRepository, BatchProcessorConfigRepository>();
            services.AddScoped<IPaymentCollectionConverter, PaymentCollectionConverter>();
            services.AddScoped<IInstructionRepository, InstructionRepository>();
            services.AddScoped<ICurrencyRepository, CurrencyRepository>();

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = _apiVersion,
                    Title = "ISOXMLValidation API",
                    Description = "ISOXMLValidationApi"
                });
                options.DocInclusionPredicate((docName, description) => true);

                // Define the BearerAuth scheme that's in use
                options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Bearer {token}\"",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey
                });

                options.OperationFilter<SecurityRequirementsOperationFilter>();
            });

            services.AddAutoMapper(typeof(Startup));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddLog4Net();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            // Enable middleware to serve generated Swagger as a JSON endpoint
            app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; });

            // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
            app.UseSwaggerUI(options =>
            {
                // specifying the Swagger JSON endpoint.
                options.SwaggerEndpoint($"../swagger/{_apiVersion}/swagger.json", $"MyProject API {_apiVersion}");
                options.DisplayRequestDuration(); // Controls the display of the request duration (in milliseconds) for "Try it out" requests.  
            });
        }
    }
}


namespace ISOXMLValidationApi.Controllers
{
    [Route("[controller]")]
    [ApiController]
    [AllowAnonymous]
    public class ISOXMLValidationController : ControllerBase, Helper.ILogger
    {
        //private readonly IConfiguration _configuration;
        //private readonly IISOXMLValidationRepository _iSOXMLValidationRepository;
        ILogger<Helper.ILogger> _logger;
        private IRuleManager _ruleManager;
        //private PaymentInfo _payment;
        //private IBatchProcessorConfigRepository _batchProcessorConfigRepository;
        //private IPaymentCollectionConverter _paymentCollectionConverter;
        public ISOXMLValidationController(/*IConfiguration configuration, IISOXMLValidationRepository iSOXMLValidationRepository,*/
            ILogger<Helper.ILogger> logger, IRuleManager ruleManager/*, PaymentInfo payment,*/
            /*IBatchProcessorConfigRepository batchProcessorConfigRepository, IPaymentCollectionConverter paymentCollectionConverter*/)
        {
            //_iSOXMLValidationRepository = iSOXMLValidationRepository;
            _logger = logger;
            //_configuration = configuration;
            _ruleManager = ruleManager;
            //_payment = payment;
            //_batchProcessorConfigRepository = batchProcessorConfigRepository;
            //_paymentCollectionConverter = paymentCollectionConverter;
        }
        /// <summary>
        /// Method to get all the validation rules for currency and country
        /// </summary>
        /// <param name="currencyCode"> default value ""</param>
        /// <param name="countryId">default value 0</param>
        /// <returns>all validate rules for currency and country</returns>
        [HttpGet]
        [Route("GetValidationRules")]
        public ActionResult GetValidationRules(string currencyCode = "", int countryId = 0)
        {
            try
            {
                _logger.LogInformation($"GetValidationRules currencyCode {currencyCode} countryId {countryId}");
                IEnumerable<IFieldRuleConfig> ccyConfigRules = _ruleManager.GetValidationRules(
                    new CurrencyCountry { CurrencyCode = currencyCode, CountryFk = countryId });

                return Ok(ccyConfigRules);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                return StatusCode(StatusCodes.Status500InternalServerError);
            }

       

}

введите описание изображения здесь

1 Ответ

0 голосов
/ 09 июля 2020

Я решил проблему, но до сих пор не понимаю, почему она не работает. Я пишу обходной путь ниже, дайте мне знать, если кто-то знает, что вызвало проблему?

Итак, на другой разработчик компьютера запускал решение из Visual Studio 2017, поэтому я запустил его с помощью Visual Studio 2019, а затем он начал работать, как ожидалось .

Но после этого я попытался запустить проект с помощью Visual Studio 2017 на моем компьютере, и он работал, как ожидалось, на моем компьютере.

  1. На его машине он работает должным образом в VS 2019, но не в VS 2017.
  2. Но на моей машине он работает как в 2019, так и в 2017 году.

Итак, дайте мне знать, в чем может быть причина root? и как заставить его работать, как указано в VS 2017, на его машине?

...