.NET 도움말 Nswag C# (How It Works For Developers) 커티스 차우 업데이트됨:6월 22, 2025 다운로드 IronPDF NuGet 다운로드 DLL 다운로드 윈도우 설치 프로그램 무료 체험 시작하기 LLM용 사본 LLM용 사본 LLM용 마크다운 형식으로 페이지를 복사하세요 ChatGPT에서 열기 ChatGPT에 이 페이지에 대해 문의하세요 제미니에서 열기 제미니에게 이 페이지에 대해 문의하세요 Grok에서 열기 Grok에게 이 페이지에 대해 문의하세요 혼란 속에서 열기 Perplexity에게 이 페이지에 대해 문의하세요 공유하다 페이스북에 공유하기 트위터에 공유하기 LinkedIn에 공유하기 URL 복사 이메일로 기사 보내기 APIs are essential in today's software development environment because they facilitate communication between various software systems and components. For developers to use APIs efficiently, there must be thorough and understandable documentation. Two effective tools that can help the C# API documentation workflow are NSwag C# and IronPDF. This post will discuss how to use NSwag to generate API specifications with .NET Core and produce high-quality PDF documents from these specifications using IronPDF. How to Use NSwag in C# Create a RESTful web API using Swagger UI. Create a C# console application. Install the NSwag library. Import the namespace and create the object. Process the Swagger JSON to C# code. Execute the code and display the result. Understanding NSwag A .NET Swagger toolchain called NSwag was created to make it easier to create Swagger specifications, or OpenAPI documents, for APIs constructed using ASP.NET Web API, ASP.NET Core, or other .NET frameworks. Features of NSwag Production of Swagger Specs Controllers, models, and .NET assemblies can all be used by NSwag to automatically produce Swagger specs. NSwag generates comprehensive documentation that covers API endpoints, request/response forms, authentication techniques, and more by examining the structure of the API code. Connectivity to .NET Projects Developers can easily include Swagger generation into their development processes by integrating NSwag with .NET projects. Developers can ensure that the documentation is updated with the codebase by adding NSwag to a .NET Core project, which will automatically produce Swagger specifications each time the project is built. Personalization and Expansion With the wide range of customization possibilities offered by NSwag, developers may easily adapt the generated Swagger specifications to meet their unique needs. Developers have control over many components of the generated documentation, including response codes, parameter explanations, and route naming conventions, through configuration settings and annotations. Getting Started with NSwag Setting Up NSwag in C# Console App The NSwag Base Class Library includes the core, Annotation, and code generation namespace, which should be available by installing from NuGet. To integrate NSwag into a C# application to generate code and Swagger specifications, and how NSwag may improve the efficiency of the development process. Implementing NSwag in Windows Console and Forms Through automated client generation, developers can efficiently produce code for accessing APIs straight from within their desktop apps by integrating NSwag into a Windows desktop application. When developing desktop applications that communicate with online services or RESTful APIs, it can be quite helpful. NSwag can be used in web applications to generate API documentation for internal APIs and client code for consuming external APIs. This aids developers in keeping their applications' frontend and backend components consistent. NSwag C# Example Here is an example of code that shows you how to use NSwag to produce C# client code: using NSwag.CodeGeneration.CSharp; using NSwag; using System.Reflection; using System.CodeDom.Compiler; using Microsoft.CodeAnalysis; using System.Net.Http; using System.IO; using System.Collections.Generic; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { using (var wclient = new System.Net.WebClient()) { // Create JSON file data from the Swagger .NET Core web API var document = await OpenApiDocument.FromJsonAsync(wclient.DownloadString("http://localhost:5013/swagger/v1/swagger.json")); var settings = new CSharpClientGeneratorSettings { ClassName = "Weather", CSharpGeneratorSettings = { Namespace = "Demo" } }; var generator = new CSharpClientGenerator(document, settings); var code = generator.GenerateFile(); var assembly = CompileCode(code); var clientType = assembly.GetType("Demo.WeatherClient"); // Replace with your actual client class name using (var httpClient = new HttpClient()) { var client = (IApiClient)Activator.CreateInstance(clientType, httpClient); var result = await client.GetWeatherForecastAsync(); foreach (var item in result) { Console.WriteLine($"Date: {item.Date} F: {item.TemperatureF} C: {item.TemperatureC} Summary: {item.Summary}"); } } } } static Assembly CompileCode(string code) { using (var memoryStream = new MemoryStream()) { var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); var references = new List<MetadataReference> { MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "Microsoft.AspNetCore.Mvc.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Private.CoreLib.dll")) }; var compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("ApiClient") .WithOptions(new Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) .AddReferences(references) .AddSyntaxTrees(Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(code)); var emitResult = compilation.Emit(memoryStream); if (!emitResult.Success) { Console.WriteLine("Compilation errors:"); foreach (var diagnostic in emitResult.Diagnostics) { Console.WriteLine(diagnostic); } return null; } memoryStream.Seek(0, SeekOrigin.Begin); return Assembly.Load(memoryStream.ToArray()); } } public interface IApiClient { // Replace with your actual method name and return type Task<List<WeatherForecast>> GetWeatherForecastAsync(); } public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF { get; set; } public string Summary { get; set; } } } using NSwag.CodeGeneration.CSharp; using NSwag; using System.Reflection; using System.CodeDom.Compiler; using Microsoft.CodeAnalysis; using System.Net.Http; using System.IO; using System.Collections.Generic; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { using (var wclient = new System.Net.WebClient()) { // Create JSON file data from the Swagger .NET Core web API var document = await OpenApiDocument.FromJsonAsync(wclient.DownloadString("http://localhost:5013/swagger/v1/swagger.json")); var settings = new CSharpClientGeneratorSettings { ClassName = "Weather", CSharpGeneratorSettings = { Namespace = "Demo" } }; var generator = new CSharpClientGenerator(document, settings); var code = generator.GenerateFile(); var assembly = CompileCode(code); var clientType = assembly.GetType("Demo.WeatherClient"); // Replace with your actual client class name using (var httpClient = new HttpClient()) { var client = (IApiClient)Activator.CreateInstance(clientType, httpClient); var result = await client.GetWeatherForecastAsync(); foreach (var item in result) { Console.WriteLine($"Date: {item.Date} F: {item.TemperatureF} C: {item.TemperatureC} Summary: {item.Summary}"); } } } } static Assembly CompileCode(string code) { using (var memoryStream = new MemoryStream()) { var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location); var references = new List<MetadataReference> { MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "Microsoft.AspNetCore.Mvc.dll")), MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Private.CoreLib.dll")) }; var compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("ApiClient") .WithOptions(new Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) .AddReferences(references) .AddSyntaxTrees(Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(code)); var emitResult = compilation.Emit(memoryStream); if (!emitResult.Success) { Console.WriteLine("Compilation errors:"); foreach (var diagnostic in emitResult.Diagnostics) { Console.WriteLine(diagnostic); } return null; } memoryStream.Seek(0, SeekOrigin.Begin); return Assembly.Load(memoryStream.ToArray()); } } public interface IApiClient { // Replace with your actual method name and return type Task<List<WeatherForecast>> GetWeatherForecastAsync(); } public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF { get; set; } public string Summary { get; set; } } } $vbLabelText $csharpLabel For the API we wish to use, we specify the Swagger specification's URL (swaggerUrl). Then the client code generated and executed into a DLL assembly is defined. OpenApiDocument is employed to load the Swagger document asynchronously from the given URL, using FromJsonAsync. To alter the generated client code, we adjust the code generator's settings (CSharpClientGeneratorSettings). In this example, the produced client code's class name and namespace are specified. From the loaded Swagger document, we construct an instance of CSharpClientGenerator and use it to produce the client code. The created client code is saved to the designated output path. We respond to any exceptions or errors that may arise during the procedure, displaying the relevant notifications on the console. NSwag Operation Generating Client Code NSwag can use a Swagger specification to generate client code in many languages, including Java, TypeScript, and C#. This makes it simple for developers to use APIs in their applications. Generating Server Code Using a Swagger specification as a basis, NSwag may also produce server code, such as ASP.NET Core controllers. This helps to scaffold server-side code for API implementations quickly. Producing Interactive API Documentation Given a Swagger specification, NSwag may produce interactive API documentation, such as Swagger UI. An interface that is easy to use is provided by this documentation for exploring and testing API endpoints. Producing Proxy Classes To integrate with SOAP-based APIs, NSwag can produce proxy classes. This enables programmers to use produced client code to access SOAP services from within their applications. Verifying Swagger Specifications NSwag is capable of verifying Swagger specifications to make sure they follow the OpenAPI/Swagger standard. This makes it easier to see any errors or discrepancies in the API documentation. Integrating NSwag with IronPDF Developers can improve the workflow for API documentation by utilizing the advantages of both technologies by integrating NSwag with IronPDF. Developers can produce thorough, offline-ready .NET web API documentation that is readily available and shareable by using NSwag to generate Swagger specifications and IronPDF to transform them into PDFs. The following procedures are part of the integration process: IronPDF excels in HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for creating PDFs from web-based content such as reports, invoices, and documentation. With support for HTML files, URLs, and raw HTML strings, IronPDF easily produces high-quality PDF documents. using IronPdf; class Program { static void Main(string[] args) { var renderer = new ChromePdfRenderer(); // 1. Convert HTML String to PDF var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"; var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent); pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf"); // 2. Convert HTML File to PDF var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath); pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf"); // 3. Convert URL to PDF var url = "http://ironpdf.com"; // Specify the URL var pdfFromUrl = renderer.RenderUrlAsPdf(url); pdfFromUrl.SaveAs("URLToPDF.pdf"); } } using IronPdf; class Program { static void Main(string[] args) { var renderer = new ChromePdfRenderer(); // 1. Convert HTML String to PDF var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"; var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent); pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf"); // 2. Convert HTML File to PDF var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath); pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf"); // 3. Convert URL to PDF var url = "http://ironpdf.com"; // Specify the URL var pdfFromUrl = renderer.RenderUrlAsPdf(url); pdfFromUrl.SaveAs("URLToPDF.pdf"); } } $vbLabelText $csharpLabel Install IronPDF Start the Visual Studio project. Choose "Tools" > "NuGet Package Manager" > "Package Manager Console". Open your command prompt and in the Package Manager Console, type the following command: Install-Package IronPdf Alternatively, you can install IronPDF by using NuGet Package Manager for Solutions. Explore and select the IronPDF package from the search results, and then click the "Install" option. Visual Studio will handle the download and installation on your behalf. NuGet will install the IronPDF package and any dependencies required for your project. After installation, IronPDF can be utilized for your project. Install Through the NuGet Website For additional information regarding IronPDF's features, compatibility, and available downloads, visit the IronPDF page on NuGet. Utilize DLL to Install Alternatively, you can incorporate IronPDF directly into your project by using its DLL file. To download the ZIP file containing the DLL, click the IronPDF download link. Unzip the file and add the DLL to your project. Implementing Logic By utilizing NSwag, developers can create API documentation and client code for using APIs more quickly by using CodeGeneration.CSharp in conjunction with IronPDF. The following steps are part of the integration workflow: Generate Client Code: To create C# client code from Swagger specs, use NSwag.CodeGeneration.CSharp. The creation of client classes and methods for communicating with the API endpoints is automated in this step. Utilize NSwag to Get Data: To produce JSON documentation from Swagger specs, use CodeGeneration.CSharp. In this stage, the request/response formats, authentication techniques, and API client endpoints are created into human-readable documentation. Convert JSON to PDF: To convert the generated code result to a PDF document, use IronPDF. In this stage, the HTML text is converted into a polished PDF document that is ready for sharing and distribution. Improve PDF Documentation: Add more content to the PDF documentation using IronPDF, such as headers, footers, watermarks, or unique branding. This stage gives developers the ability to personalize the PDF documentation's look and branding to suit their tastes. using IronPdf; using System.Text; using System.Collections.Generic; StringBuilder sb = new StringBuilder(); foreach (var item in result) { sb.Append($"<p>Date: {item.Date} F: {item.TemperatureF} C: {item.TemperatureC} Summary: {item.Summary}</p>"); } var renderer = new HtmlToPdf(); var pdf = renderer.RenderHtmlAsPdf(sb.ToString()); pdf.SaveAs("output.pdf"); Console.WriteLine("PDF generated successfully!"); Console.ReadKey(); using IronPdf; using System.Text; using System.Collections.Generic; StringBuilder sb = new StringBuilder(); foreach (var item in result) { sb.Append($"<p>Date: {item.Date} F: {item.TemperatureF} C: {item.TemperatureC} Summary: {item.Summary}</p>"); } var renderer = new HtmlToPdf(); var pdf = renderer.RenderHtmlAsPdf(sb.ToString()); pdf.SaveAs("output.pdf"); Console.WriteLine("PDF generated successfully!"); Console.ReadKey(); $vbLabelText $csharpLabel The code above accesses the retrieved data from the result object and appends the fields Date, TemperatureF, TemperatureC, and Summary to paragraphs in a loop. It then specifies the output file path for the PDF, then notifies the user that a PDF has been generated successfully. Below is the result from the above code. Conclusion CodeGeneration NSwag technologies like CSharp and IronPDF work well together to streamline client code production and API documentation processes. Developers may speed up the creation of API-driven solutions, automate the creation of API documentation, and produce professional-looking PDF publications by integrating these tools into C# applications. NSwag.CodeGeneration.CSharp with IronPDF offers developers a complete solution for efficiently documenting APIs and producing client code in C#, whether they are developing desktop, web, or cloud-based apps. The Lite bundle includes a perpetual license, one year of software maintenance, and an upgrade to the library. IronPDF offers free licensing with restrictions on redistribution and time. Users can assess the solution during the trial period without having to see a watermark. For additional information on the price and license, please see IronPDF's licensing information. Go to the Iron Software libraries page for additional information about Iron Software's product libraries. 자주 묻는 질문 C#으로 API 사양을 생성하는 데 NSwag가 어떤 도움을 줄 수 있나요? NSwag는 .NET Core 프로젝트에서 Swagger 또는 OpenAPI 문서로 알려진 API 사양을 자동으로 생성할 수 있습니다. 이렇게 하면 API 문서가 항상 코드베이스와 동기화됩니다. Swagger 사양을 PDF 문서로 변환하는 과정은 어떻게 되나요? Swagger 사양을 PDF 문서로 변환하려면 IronPDF를 사용하면 됩니다. 먼저 NSwag를 사용하여 Swagger 사양을 생성한 다음 IronPDF를 사용하여 이러한 사양의 HTML 콘텐츠를 고품질 PDF로 변환합니다. NSwag를 .NET 프로젝트에 통합하려면 어떻게 해야 하나요? .NET 프로젝트에 NSwag를 통합하려면 NuGet을 통해 NSwag 라이브러리를 설치하고, 빌드 프로세스 중에 Swagger 사양을 생성하도록 구성하고, 생성된 사양을 문서화 및 코드 생성에 사용해야 합니다. NSwag는 Swagger 사양에서 클라이언트 코드와 서버 코드를 모두 생성할 수 있나요? 예, NSwag는 단일 Swagger 사양에서 C#, Java, TypeScript와 같은 언어의 클라이언트 코드와 ASP.NET Core 컨트롤러와 같은 서버 측 코드를 모두 생성할 수 있습니다. IronPDF는 API 문서화 워크플로우를 어떻게 개선하나요? IronPDF는 개발자가 HTML 기반 API 문서를 전문적이고 공유 가능한 PDF 문서로 변환하여 오프라인에서 정보에 액세스할 수 있도록 함으로써 API 문서 워크플로우를 개선합니다. Visual Studio 프로젝트에서 IronPDF를 사용하려면 어떤 단계가 필요하나요? Visual Studio 프로젝트에서 IronPDF를 사용하려면 NuGet 패키지 관리자를 통해 IronPDF를 검색하고 '설치'를 클릭하여 설치하거나 패키지 관리자 콘솔에서 Install-Package IronPdf 명령을 사용하여 설치할 수 있습니다. NSwag를 사용하여 대화형 API 문서를 어떻게 생성할 수 있나요? NSwag는 브라우저에서 직접 API 엔드포인트를 탐색하고 테스트할 수 있는 사용자 친화적인 인터페이스를 제공하는 Swagger UI를 제작하여 대화형 API 문서를 생성할 수 있습니다. API 문서에 NSwag를 사용하면 어떤 이점이 있나요? NSwag는 API 문서 생성을 자동화하여 코드베이스가 항상 최신 상태로 유지되도록 합니다. 또한 대화형 문서 및 클라이언트 측 코드 생성을 지원하여 개발 프로세스를 간소화합니다. IronPDF는 HTML 콘텐츠와 어떻게 작동하여 PDF를 생성하나요? IronPDF는 렌더링 엔진을 사용하여 CSS 및 JavaScript를 포함한 HTML 콘텐츠를 PDF 형식으로 변환하므로 웹 기반 콘텐츠에서 오프라인에서 사용할 수 있는 정밀한 문서를 만드는 데 이상적입니다. 커티스 차우 지금 바로 엔지니어링 팀과 채팅하세요 기술 문서 작성자 커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다. 커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다. 관련 기사 업데이트됨 12월 11, 2025 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 더 읽어보기 업데이트됨 12월 20, 2025 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 더 읽어보기 업데이트됨 12월 20, 2025 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기 Dapper C# (How It Works For Developers)Flunt C# (How It Works For Developers)
업데이트됨 12월 11, 2025 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 더 읽어보기
업데이트됨 12월 20, 2025 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 더 읽어보기
업데이트됨 12월 20, 2025 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기