Dave
Dave

Reputation: 7379

WebApi/.net-core: Can't access to webapi

I cant access to webapi from postman

the error is the next:

enter image description here

As you see no authoritation.

valuescontroller.cs is:

namespace CVService.Controllers
{
    [Route("api/[controller]")]

    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

Program.cs is:

namespace CVService
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

startup.cs is:

namespace CVService
{
    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.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
            }));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

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

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

I thought it was a problem of Cors and I added the library but same problem.

the command I use is dotnet run from terminal, I am using SDK version 2.1.301.

dotnet --info

SDK de .NET Core (reflejando cualquier global.json):
 Version:   2.1.301
 Commit:    59524873d6

Entorno de tiempo de ejecución:
 OS Name:     Windows
 OS Version:  10.0.16299
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\2.1.301\

Host (useful for support):
  Version: 2.1.1
  Commit:  6985b9f684

.NET Core SDKs installed:
  2.1.301 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.1 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.1.1 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.1.1 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download

Why can't I access? what is wrong?

Upvotes: 2

Views: 7118

Answers (2)

ezgienise
ezgienise

Reputation: 1

Three steps to solve this issue:

  1. Inside of your Startup.cs file's Configure method, add this code:

     app.UseEndpoints(endpoints =>
      {
          endpoints.MapControllerRoute(
              name: "default",
              pattern: "{controller=Home}/{action=Index}/{id?}");
      });
    
  2. Change your controller's route like this:

       [Route("api/[controller]/[action]")]
    
  3. It's better to add to your action constructor a pattern like [FromQuery]; than you can call your API like this:

           api/Values/Get?id=5
    

Upvotes: 0

Nkosi
Nkosi

Reputation: 247641

Why can't I access? what is wrong?

You are calling the wrong URL.

GET api/values/get

does not exist according to the attributes used.

Call

GET api/values 

The comments in the code example actually show you what paths are available to call based on the actions in the controller

// GET api/values
// GET api/values/5
// POST api/values
// PUT api/values/5
// DELETE api/values/5

Reference Routing to controller actions in ASP.NET Core

Upvotes: 5

Related Questions