Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Swagger

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, I would like to share with you the relevant knowledge of how to use Swagger. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Swagger can be very convenient for the release of WebApi automatically generate elegant documents, do not need to write their own extra, just need to configure the project, is a very useful tool.

1. Import Swashbuckle package using HuGet

2. Modify SwaggerConfig.cs

When the Swashbuckle is imported, the SwaggerConfig.cs is automatically generated under the App_Start folder of the site to configure the Swagger page. There are a lot of things to configure, and the following is a list of simple configurations that I personally need (because nothing else has been studied).

1publicclassSwaggerConfig

2 {

3publicstaticvoidRegister ()

4 {

5varthisAssembly=typeof (SwaggerConfig). Assembly

six

7GlobalConfiguration.Configuration

8.EnableSwagger (c = >

9 {

10c.SingleApiVersion ("v1", "MyWebApi") .contact (x = >

11 {

12x.Name ("Bobbie"); / / configuration interface header description

13})

fourteen

15c.IncludeXmlComments (GetXmlCommentsPath ("/ bin/WarRoom.WebApi.XML")); / / configure the template XML path

sixteen

17})

18.EnableSwaggerUi (c = >

19 {

C.InjectJavaScript (Assembly.GetExecutingAssembly (), "MyWebApi.Scripts.Swagger_CN.js"); / / configure the Chinese js file

20})

21}

twenty-two

23privatestaticstringGetXmlCommentsPath (stringXmlPath)

24 {

25 percent @ "{System.AppDomain.CurrentDomain.BaseDirectory}" + XmlPath

26}

27}

3. Configure project properties

The main purpose is to set up several configurations under "generation", which I drew a red box. Here is an explanation of the functions of several configurations:

(1) disable warning 1591 is a warning that forbids the lack of comments, otherwise classes and functions without header comments will have an underscore of the warning, which looks uncomfortable (but the warning does not affect the use).

(2) check the XML document file to automatically generate a path that is consistent with the one configured in SwaggerConfig.cs:

C.IncludeXmlComments (GetXmlCommentsPath ("/ bin/WarRoom.WebApi.XML"))

As a result, the configuration has actually been completed, so let's test it:

4. Test

Create a new Controller with the file name DemoController.cs:

1publicclassDemoController:ApiController

2 {

3///

4Compact / I am the PostTest method

5///

6Universe / Parameter 1

7///

8 [HttpGet]

9publicstringPostTest (stringname)

10 {

11stringresult = "Hello" + name

12returnresult

13}

Then run it and visit localhost:27827/Swagger (URL port to see your own project), and you can see that the following interface is successful:

The page automatically generates basic information such as interface path, interface function, comments, parameters, etc., and also provides interface test function (click TryitOut), which can test the interface (you can enter parameters directly).

5. Sinicization

Some friends like Chinese. Here we also test the Chinese feature. The main thing is to add a JS file with Chinese feature and import it in the SwaggerConfig.cs configuration:

(1) create a new file named Swagger_CN.js and put it under the Scripts folder:

1 roomusestrict`

2Candlestick *

3*Translatorfordocumentationpages.

4 *

5*Toenabletranslationyoushouldincludeoneoflanguage-filesinyourindex.html

6*after.

7 million Forexample-

8 *

9*Ifyouwishtotranslatesomenewtexstsyoushoulddotwothings:

10*1.Addanewphrasepair ("NewPhrase": "NewTranslation") intoyourlanguagefile (forexamplelang/ru.js) Itwillbegreatifyouadditinotherlanguagefilestoo.

11*2.MarkthattextittemplatesthiswayNewPhraseor.

12 minutes ThemainthinghereisattributedataAfter translate.Onlyinnerhtml title Mill attribution and valueMile attributearegoingtotranslate.

13 *

1400 /

15window.SwaggerTranslator = {

16_words: []

17translate:function () {

18var$this=this

19 $('[data-sw-translate]') .each (function () {

20 $(this) .html ($this._tryTranslate ($(this) .html ()

21 $(this) .val ($this._tryTranslate ($(this) .val ()

22 $(this) .attr ('title',$this._tryTranslate ($(this) .attr (' title')

23})

24}

25_tryTranslate:function (word) {

26returnthis._words [$.trim (word)]! = = undefined?this._words [$.trim (word)]: word

27}

28learn:function (wordsMap) {

29this._words=wordsMap

30}

31}

32/*jshintquotmark:double*/

33window.SwaggerTranslator.learn ({

34 "Warning:Deprecated": "warning: out of date"

35 "ImplementationNotes": "implementation remarks"

36 "ResponseClass": "response class"

37 "Status": "status"

38 "Parameters": "parameters"

39 "Parameter": "parameters"

40 "Value": "value"

41 "Description": "description"

42 "ParameterType": "Parameter type"

43 "DataType": "data type"

44 "ResponseMessages": "response message"

45 "HTTPStatusCode": "HTTP status code"

46 "Reason": "reason"

47 "ResponseModel": "response Model"

48 "RequestURL": "request URL"

49 "ResponseBody": "Responder"

50 "ResponseCode": "response code"

51 "ResponseHeaders": "response head"

52 "HideResponse": "Hidden response"

53 "Headers": "head"

54 "Tryitout!": "try it!"

55 "Show/Hide": "Show / hide"

56 "ListOperations": "display operation"

57 "ExpandOperations": "unfold operation"

58 "Raw": "original"

59 "can'tparseJSON.Rawresult": "unable to parse JSON. Original result"

60 "ModelSchema": "Model Architecture"

61 "Model": "Model"

62 "apply": "Application"

63 "Username": "user name"

64 "Password": "password"

65 "Termsofservice": "terms of Service"

66 "Createdby": "founder"

67 "Seemoreat": "View more:"

68 "Contactthedeveloper": "contact developers"

69 "apiversion": "api version"

70 "ResponseContentType": "response content type"

71 "fetchingresource": "getting resources"

72 "fetchingresourcelist": "getting resource list"

73 "Explore": "browsing"

74 "ShowSwaggerPetstoreExampleApis": "Show SwaggerPetstore sample Apis"

75 "Can'treadfromserver.Itmaynothavetheappropriateaccess-control-originsettings.": "cannot be read from the server. Access-control-origin may not be set correctly."

76 "Pleasespecifytheprotocolfor": "Please specify the protocol:"

77 "Can'treadswaggerJSONfrom": "unable to read swaggerJSON in"

78 "FinishedLoadingResourceInformation.RenderingSwaggerUI": "Resource information loaded. Rendering SwaggerUI"

79 "Unabletoreadapi": "unable to read api"

80 "frompath": "from path"

81 "serverreturned": "Server returns"

82})

83 $(function () {

84window.SwaggerTranslator.translate ()

85})

(2) set Swagger_CN.js to "embedded resources"

Property-> build Action-> set to embedded Resources

(3) configure SwaggerConfig.cs

Under EnableSwaggerUi, add:

C.InjectJavaScript (Assembly.GetExecutingAssembly (), "MyWebApi.Scripts.Swagger_CN.js")

Note: MyWebApi.Scripts.Swagger_CN.js format is: project name. Folder name .JS file name

You can see the configuration of the SwaggerConfig.cs file above. Then run it again.

These are all the contents of the article "how to use Swagger". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report