How to use [HttpPost], [HttpGet] in ASP.NET Core Web API

daowdos 261 Reputation points
2021-08-01T15:05:07.703+00:00

Hi,
I'm trying to build my app with Web API, but I just don't understand how it works, I read the Microsoft Learn but couldn't figure it out.

and I can't run my project.

"ValuesController.cs" :

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpPost]
[Route("shop")] // What is the Rout for ?
public string AddProduct(string productName, string categoryName, double price,
int stock, string productDescription,
string productOverview, string productImage)
{
return BLL.AddProduct(productName, categoryName, price,
stock, productDescription, productOverview, productImage);
}

I don't understand this property in "launchSettings.json" -

"launchUrl": "somestringforurl",

  • Is it only the name of the URL nothing else ?nothing opens my "ValuesController.cs" file.

Thanks in advance

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,189 questions
Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,426 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,278 questions
{count} votes

11 answers

Sort by: Most helpful
  1. Duane Arnold 3,216 Reputation points
    2021-08-01T19:37:13.67+00:00

    Where is the client program that is going to consume the Webservice?

    If you look at the GetALL() code you will see the formulated URL used to access th controller's action method.

    https://github.com/darnold924/PublishingCompany/blob/master/ServiceLayer/AuthorSvc.cs

    I can take the URL and paste into the WebAPI project that's running browser's address bar debug mode, the code will be execute in the WebAPI and the results returned in the browser page.

    Your other option is to use Postman.

    https://www.geeksforgeeks.org/introduction-postman-api-development/#:~:text=Postman%3A%20Postman%20is%20an%20API,build%2C%20test%20and%20modify%20APIs.&text=It%20has%20the%20ability%20to,(like%20JavaScript%2C%20Python).

    1 person found this answer helpful.

  2. Zhi Lv - MSFT 32,016 Reputation points Microsoft Vendor
    2021-08-03T09:58:06.687+00:00

    Hi @Elado,

    I don't understand this property in "launchSettings.json" -

    "launchUrl": "somestringforurl",

    Is it only the name of the URL nothing else ?nothing opens my "ValuesController.cs" file.

    The launchUrl property in the "launchSettings.json" specify the URL for a page that you want to open when you start debugging your project.

    For example, when we create a new Asp.net Core API application, by default the launchUrl property value is swagger, when we running the application, the result as below:

    120126-image.png

    After adding the ValuesController API controller, and change the launchUrl property value to api/values, the result as below:

    120151-image.png

    [Note] we are running the application via IIS express. More detail information about the launchSettings file, you could check Development and launchSettings.json

    The ValuesController as below:

    [Route("api/[controller]")]  
    [ApiController]  
    public class ValuesController : ControllerBase  
    {  
        // GET: api/<ValuesController> // api/values  
        [HttpGet]  
        public IEnumerable<string> Get()  
        {  
            return new string[] { "value1", "value2" };  
        }  
    
        // GET api/<ValuesController>/5   
        [HttpGet("{id}")]      //https://localhost:44319/api/values/6   
        public string Get(int id)  
        {  
            return "value: "+ id.ToString();  
        }  
    
        // POST api/<ValuesController>  
        [HttpPost]  
        public void Post([FromBody] string value)  
        {  
        }  
     
    }  
    

    How to use [HttpPost], [HttpGet] in ASP.NET Core Web API

    To answer this question, I suggest you check the Startup.cs file first, as you can see that I didn't add any other route template.

        public void ConfigureServices(IServiceCollection services)  
        {  
    
            services.AddControllers();  
            services.AddSwaggerGen(c =>  
            {  
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPISample", Version = "v1" });  
            });  
        }  
    
        // 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.UseSwagger();  
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPISample v1"));  
            }  
    
            app.UseHttpsRedirection();  
    
            app.UseRouting();  
    
            app.UseAuthorization();  
    
            app.UseEndpoints(endpoints =>  
            {  
                endpoints.MapControllers();  
            });  
        }  
    

    To access the Values API methods, the request URL as below:

    https://localhost:44319/api/values/ => access the HttpGet method without parameter
    https://localhost:44319/api/values/6 => access the HttpGet method with parameter.

    When the action contains the [HttpGet] or [HttpPost] attribute (without the template string), it restricts the matching to only HTTP GET or Post requests.

    When using the HTTP attribute with template string, for example: [HttpGet("{id}")], therefore id is appended to the "api/[controller]" template on the controller. The methods template is "api/[controller]/"{id}"". Therefore this action only matches GET requests for the form /api/test2/xyz,/api/test2/123,/api/test2/{any string}, etc.

    If we set the attribute as [HttpGet("apimethod/{id}")], the methods template is "api/[controller]/apimethod/"{id}"", and then the action request url will be: https://localhost:44319/api/values/apimethod/6

    If we set the attribute as [HttpGet("/apimethod/{id}")], the methods template is "/apimethod/"{id}"", and then the action request url will be: https://localhost:44319/apimethod/6

    The [Route] attribute is similar, because all the HTTP verb templates are route templates.

    You could refer this sample screenshot:

    120144-1.gif

    More detail information, you can check the Routing to controller actions in ASP.NET Core (check the Attribute routing with Http verb attributes part).


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    1 person found this answer helpful.

  3. Alberto Poblacion 1,556 Reputation points
    2021-08-01T16:44:44.417+00:00

    The launchurl is the URL for a page that you want to open when you start debugging your project. You would need to add such page to your project. It is not really very important for a web api project. For a web api, you don´t care about opening a page; instead an external program will invoke different APIs within your project.

    [Route("shop")] // What is the Rout for ?

    This overrides the default routing configured for the project. Instead of forcing the route to be api/controllerName and have your method name match the HTTP verb (the default), you can instead specify the verb with an attribute such as [HttpPost] and also use [Route] to specify that the URL for invoking your method be something different (in this case "shop").


  4. Duane Arnold 3,216 Reputation points
    2021-08-01T17:55:12.377+00:00

    https://learn.microsoft.com/en-us/visualstudio/debugger/how-to-enable-debugging-for-aspnet-applications?view=vs-2017

    You start WebAPI project un in visual stuido. And if you have the project to start using the browser, then you drop a URL to the controller action method in the browser's address bar.


  5. daowdos 261 Reputation points
    2021-08-02T09:54:23.247+00:00

    @Duane Arnold
    So is this really the new method (?) to copy and paste manually a path to the URL ? It sound to me incorrect, not just that but I can't even open the browser (ctrl+f5) without getting an error that nothing was found.

    It's like I didn't ask nothing, it's all the same including my undrestanding of how the code should be.