简体   繁体   中英

How to debug Web Api class library

I have a Asp.Net WebApi project. I have a created a class library and I have added controllers and models into it.

The project structure is explained in another StackOverflow question .

QUESTION:

Now I need to debug the controllers in the class library. What is the easiest way to do it?

UPDATE My question is about debugging a class library in visual studio 2015. As it's a class library which needs to attached to a process of running WabApi project.

So when I click debug button in VS, the WEBAPI process needs to be started and attached to class library debug session automatically.

In visual studio project properties, there is a debug option to set "Start External Program". How can I associate the WebApi project here? Or is there any alternative?

I believe the easiest way is creating a console application to host your web api, then you can use a tool like fiddler /postman to send requests to your api.

https://docs.microsoft.com/en-us/aspnet/web-api/overview/older-versions/self-host-a-web-api

First of all, your WEB API project should contain your controllers, not your class library.

The stack overflow you've shown, is a really bad practice, as your WEB API serves as an entry point (PRESENTATION LAYER ) for your application.

You indeed can make a Library 'Models' for your Domain models, but should also make a Library for accessing your database, called the Data Access Layer ( DAL ).

If you want to add some business logic to it, you need a 4th Library called the business layer ( BL ).

So the flow should be like this:

Client <-> Presentation Layer <-> Business Layer <-> Data Access Layer <-> Database.

The PL, BL and DAL can have references to the Model Library. This whole layer thing is called an N Tier Architecture.

You should also take a look at the MVC pattern for your presentation layer.

OK now that the architecture is done, it's very simple to actually debug / test your controllers.

A first option could be to use POSTMAN to send data to you Controllers endpoint, and just add a breakpoint to the controller and debug step by step.

A second option is to use Swagger, which will provide you with a user friendly interface of your controller's endpoints, and also the ability to actually send stuff to it. It will also give you a template JSON of how the message needs to be structured.

More info on the N Tier and MVC

N Tier: https://en.wikipedia.org/wiki/Multitier_architecture

MVC: https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

Swagger tutorial: https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger

Regards!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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