浏览器在输入`dotnet run`命令时返回错误404。

huangapple go评论53阅读模式
英文:

Browser returns error 404 when command `dotnet run` is entered

问题

I'm having some issues with .NETCore, I'm making a simple WebApi for college, but whenever I run dotnet run command on my Windows terminal I get the following output:

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\Users\recru\source\repos\prova-dotnetcore\WebApi

But on my browser I get the error 404. Please help me. This is my Startup.cs:

C:\...\WebApi

This is a simple Login route on my controller:

C:\...\UserController.cs

And finally this is the WebApi.csproj:

C:\...\WebApi.csproj

This is my "C:\Program Files\dotnet" folder

Please help me! Thanks a Lot everyone, let me know if you need any more information about my project!

英文:

I'm having some issues with .NETCore, I'm making a simple WebApi for college, but whenever I run dotnet run command on my Windows terminal I get the following output:

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\Users\recru\source\repos\prova-dotnetcore\WebApi

But on my browser I get the error 404. Please help me. This is my Startup.cs:

using Application.Context;
using Application.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
using System;


namespace WebApi
{
    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.AddDbContext<ProvaContext>(opt => opt.UseInMemoryDatabase("ProvaDoubleIt"));
            services.AddTransient<IProdutoService, ProdutoService>();
            services.AddTransient<ICategoriaService, CategoriaService>();
            services.AddTransient<IUsuarioService, UsuarioService>();
            services.AddControllers();

            // Add authentication
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                var issuer = Configuration["Jwt:Issuer"];
                var audience = Configuration["Jwt:Audience"];
                var key = Configuration["Jwt:Key"];

                if (string.IsNullOrEmpty(issuer))
                {
                    throw new ArgumentNullException(nameof(issuer));
                }

                if (string.IsNullOrEmpty(audience))
                {
                    throw new ArgumentNullException(nameof(audience));
                }

                if (string.IsNullOrEmpty(key))
                {
                    throw new ArgumentNullException(nameof(key));
                }

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = issuer,
                    ValidAudience = audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key))
                };
            });

            // Add Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "API da Prova DotNetCore", Version = "v1" });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = @"JWT Authorization header using the Bearer scheme. 
                          Enter 'Bearer' [space] and then your token in the text input below.
                          Example: 'Bearer 12345abcdef'",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer"
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                    }
                },
                Array.Empty<string>()
            }
        });
            });
        }

        // 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.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

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

    }
}

This is a simple Login route on my controller:

using System.Threading.Tasks;
using Application.Services;
using Microsoft.AspNetCore.Mvc;

namespace WebApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;

        public UserController(IUserService userService)
        {
            _userService = userService;
        }

        [HttpPost("login")]
        public async Task<IActionResult> Login(string email, string password)
        {
            var result = await _usuarioService.DoLogin(email, password);

            if (result == null)
            {
                return BadRequest("Email or password incorrect");
            }

            return Ok("User logged in!.");
        }
    }
}

And finally this is the WebApi.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">

	<PropertyGroup>
		<TargetFramework>netcoreapp3.1</TargetFramework>
		<StartupObject>WebApi.Program</StartupObject>
	</PropertyGroup>

	<ItemGroup>
		<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="5.0.1" />
		<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.0" />
		<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
	</ItemGroup>

	<ItemGroup>
		<ProjectReference Include="..\Application\Application.csproj" />
	</ItemGroup>

</Project>

This is my "C:\Program Files\dotnet" folder

Please help me! Thanks a Lot everyone, let me know if you need any more information about my project!

答案1

得分: 2

只是为了告诉大家,我现在已经在处理所有的事情,包括使用以下代码来使用Swagger

 app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "API da Prova DotNetCore");
                });

感谢你的帮助,它为我解决这个代码的问题提供了一个起点!

英文:

Just to update everyone, I got everything on the works now, including Swagger using the following code

 app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "API da Prova DotNetCore");
                });

Thanks for your help, it gave somewhere to begin on solving my issues on this code!

huangapple
  • 本文由 发表于 2023年4月10日 22:22:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75977931.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定