简体   繁体   English

ASP.Net Core 3.0 应用程序 URL 未找到路径参数

[英]ASP.Net Core 3.0 app URL was not found with Path parameters

we have defined AddMvc() and UseMvc() methods in our startup.cs file bur, however, the controller action is not found by hitting the URL directly as below我们已经在我们的startup.cs文件bur中定义了AddMvc()UseMvc()方法,但是,通过直接点击URL找不到控制器动作,如下所示

https://localhost:44384/api/weatherforecast/getmyWeather/10 

isn't working in our browser, however, https://localhost:44384/api/weatherforecast/getmyWeather & https://localhost:44384/api/weatherforecast/getmyWeather?id=10 works在我们的浏览器中不起作用,但是, https://localhost:44384/api/weatherforecast/getmyWeather & https://localhost:44384/api/weatherforecast/getmyWeather?id=10有效

Startup.cs启动文件

public class Startup
    {
        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.AddMvc(options => options.EnableEndpointRouting = false);

        }

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

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            //app.UseEndpoints(endpoints =>
            //{
            //    endpoints.MapControllers();
            //});
            app.UseMvc(routes => { routes.MapRoute("default", "api/{controller=Default}/{action=Index}/{id?}"); });
        }
    }

And on WeatherForecastController.csWeatherForecastController.cs 上

[ApiController]
    [Route("api/[controller]")]

    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        [Route("getmyWeather")]
        public IEnumerable<WeatherForecast> getmyWeather(int id)
        {
            var rng = new Random(id);
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }

Not sure why Path parameters in URL are not working but querystrings does.不知道为什么 URL 中的 Path 参数不起作用,但 querystrings 起作用。 what am I missing here?我在这里错过了什么?

In order to use conventional routes for API , you need to disable attribute route on API .为了使用API常规路由,您需要禁用API上的属性路由。 In your startup.cs:在您的 startup.cs 中:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
          endpoints.MapControllerRoute(
            name: "Default",
            pattern: "{controller=default}/{action=Index}/{id?}");
        });
    }

And your Controller will look like:你的Controller看起来像:

    //[ApiController]
    //[Route("api/[controller]")]    
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"};

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    [Route("getmyWeather")]
    public IEnumerable<WeatherForecast> getmyWeather(int id)
    {
        var rng = new Random(id);
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

OR you can create your own custom base controller and use that:或者您可以创建自己的自定义基本控制器并使用它:

[Route("api/[controller]/[action]/{id?}")]
[ApiController]
public class MyBaseController : ControllerBase
{
}

And your Controller :还有你的Controller

public class WeatherForecastController : MyBaseController 
{
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"};

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    [Route("getmyWeather")]
    public IEnumerable<WeatherForecast> getmyWeather(int id)
    {
        var rng = new Random(id);
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM