question

Elado avatar image
0 Votes"
Elado asked ZhiLv-MSFT commented

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

Hi,
I'm trying to build my app with Web API, but I just don't understand how it works, I read the Microsoft docs 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

dotnet-csharpwindows-apidotnet-aspnet-core-webapi
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

You cannot easily understand ASP.NET Core Web API if you don't embrace the RESTful API paradigm and the MVC design pattern (and its URL patterns). Swagger is there to assist though.

0 Votes 0 ·

Hi @Elado,

I can't run my project.

Do you meet any error? If meet any error, please share the detailed error message.




0 Votes 0 ·
ZhiLv-MSFT avatar image
1 Vote"
ZhiLv-MSFT answered ZhiLv-MSFT commented

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


image.png (80.1 KiB)
image.png (57.3 KiB)
1.gif (534.9 KiB)
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank you very much @ZhiLv-MSFT
I read your answer,

One thing I dont understand is why I was told in these docs that this is much better way to use than the WebService WebMethod, while WebAPI is to only to check the SQL data, but not pass/send data to the SQL as WebService webmethods.

0 Votes 0 ·

One thing I dont understand is why I was told is these docs that this is much better way than the WebService

This has been explained several times in your other threads. Your current ASMX source code serializes a product list to JSON format. Then returns the JSON string in a SOAP message. This is poor design because the client has no idea what JSON data to expect.

Also, explained in your other threads, ASMX and WebMethod is an XML/SOAP technology. Your source code is not taking advantage of standard SOAP features like the WSDL to generate code. According to your source code, you are trying to convert ASMX to a JSON service. Web API is already a JSON service. It makes more sense to use Web API since it matches your requirement.

Simply, Web API is a better tool for what your code is trying to do.

WebMethod, if only to check the SQL data, not passing data to the SQL.

Can you explain this comment? It seems you think a WebMethod is only used to read data which is not true.


0 Votes 0 ·

WebMethod as I tried to say
Is to pass data, update,delete, and get data.

I don’t understand what is SOAP message, I only use what I get, I got no control on the types - SOAP , XML.
I need the JSON

0 Votes 0 ·
Show more comments
Elado avatar image
0 Votes"
Elado answered AgaveJoe edited

@DuaneArnold-0443
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.

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Either you find a way to copy/paste the known URL from a client side program, becuase I made the URL(s) up on the client-side program that's going to consume the WebAPI in the example code and just copy paste the URL not having to to start the client-side program to test the WebAPI.

Or you enter every last bit of the URL into the browser's address bar. Those are your choices, and you are not coming around not knowing what the URL is to a WebAPI controller action method. It doesn't matter if you were using Postman either. Now you can do some wild goose chasing and that's on you.

0 Votes 0 ·

Web API is a mature RESTful service framework that takes advantage of standard HTTP action; GET, POST, PUT, DELETE. Web API uses the HTTP method to select a controller action. Your code example overrides this behavior using routing attributes.

Your [HttpPost] action defines individual parameters. Typically, a model with multiple properties is expected. It seems you do not understand the fundamentals and are making assumptions. I recommend going through a few beginning level tutorials to learn basic Web API constructs and programming patterns. Focus on HTTP, Routing, and Model Binding.

The previous links target ASP.NET. If you are building a Core app then see the Core fundamental docs.


0 Votes 0 ·
DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered DuaneArnold-0443 commented

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).

· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Sorry Duane but I don't understand what you are trying to explain here.

You are showing me other code with no [HttpPost]/ [HttpGet].
And I'm not about to install another software as Postman, I have enough - SQL Server and Visual studio 2019
I want to make it simple and working.
Just run ctrl+f5 and open the method and choose from them which to invoke.

0 Votes 0 ·

Know what is happening between the URL(s) to WebAPI controller methods and the service layer classes that are doing CRUD operations via a WebAPI with a data access layer(DAL) that sitting behind the WebAPI that the URL for a given controller action must be known by the client side software.

On that same token, in debugging the WebAPI that is hosted by Visual Stuido, the same URL must be known by you that you will enter into the browser's address bar if you expect to invoke the code in a controller's action method including any data or the parms the WebAPI controller method expects.

https://github.com/darnold924/PublishingCompany

I gave you the information the link on how to set VS up to debug an ASP.NET Core solution, and that in order to debug the WebAPI you must enable the browser feature that brings up the browser so that you can give the URL to the WebAPI controller action method to invoke the controller's action method while the WebAPI hosted by VS is in debug mode.

0 Votes 0 ·
DuaneArnold-0443 avatar image
0 Votes"
DuaneArnold-0443 answered Elado commented

https://docs.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.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Can it work as webservice in the screen shot ??

What do you mean by "drop a URL to the controller action method" ? why do I need all this hard coded ?
119663-webservice.png


0 Votes 0 ·
webservice.png (17.1 KiB)
APoblacion avatar image
0 Votes"
APoblacion answered Elado edited

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").

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

So how can run it? I get error in chrome

119604-work.png


0 Votes 0 ·
work.png (129.3 KiB)