#Asp.Net Razor Pages
Explore tagged Tumblr posts
i4technolab · 2 years ago
Text
Razor Page is similar to the HTML page but it loads data easily. A Razor Page is almost the same as ASP.NET MVC’s view component. It has basically the syntax and functionality the same as MVC. Razor pages vs. MVC in ASP.NET
1 note · View note
fretzine · 2 years ago
Text
Uncle Bob, Alan Turing and Razors.
It's been some time since I've updated the blog with my software development news. It's been a busy two months filled with Java exams, web building, work project deliverables and milestones and a sense of impending doom at the THREE 4 hour exams that I have to sit this week.
That being said, I still like to take the time to discuss some of the interesting things that I've been reading and watching lately. So in this article I will quickly discuss and link to videos across the interwebs that share some very cool ideas that I have encountered during my studies and work.
Uncle Bob's Clean Code
If you haven't heard of Uncle Bob then you need to watch his videos on Clean Code that can be found for free on YouTube. Robert Martin is a highly influential software programmer who was one of the original authors of the Agile manifesto (when it was designed for programmers before the project managers took over). He is known for promoting many different software programming principles, including the well known SOLID principle.
His lectures are fun but more importantly very important to learn.
youtube
The Halting Problem
With the development of such powerful computers you'd imagine that the pool of tasks that couldn't be completed by a program would either be small or shrinking. Well, it turns out that it has stayed relatively the same size (at least for the last 20 years). There are some algorithms, some procedures and predicates that cannot be solved by any computer, even supercomputers. One of the many problems that cannot be solved was proven so by Alan Turning. It is called the Halting Problem and it's quite interesting. The video below is a very brief introduction but sums it up nicely and skips all of the logic for those who just want the high level summary.
youtube
Razor Pages ( .Net)
I have been working as a web developer for 6 months now and during this time I've been so busy catching up with the current major project which requires very little code that we have yet to delve into any real web design. I've been dealing with small amounts of javascript here and there and designed the odd banner or two in CSS but I have mainly been working on service design and continual service improvement.
This month will see me start diving into the world of .Net from Microsoft. I've been beginning my scouring of their documentation and support sites (Microsoft actually provides good documentation that explains key concepts with very little fuss.) Below is a playlist of introductory lessons from Microsoft and a great starting place for anyone who wants to get into ASP.NET or .NET web developing.
youtube
I'm hoping that someone somwhere is interested in any of these videos, if you are let me know on twitter @alexheywood and I will get in touch and we can share resources!
Desperately trying to remind myself that its summer outside and that I should not spend all of my time coding / watching videos on coding.
Speak soon!
6 notes · View notes
ryadel · 2 years ago
Link
2 notes · View notes
Text
Top Skills You Need to Master .NET Development in 2025
If you're searching for the best .NET training in Hyderabad, you're already on the right path. .NET remains one of the most powerful frameworks for building scalable, secure, and high-performance applications. As we move into 2025, here are the top skills every aspiring .NET developer must master.
1. Master C# Programming
C# is the primary language for .NET development. Understanding object-oriented programming, LINQ, and asynchronous programming in C# is critical for building modern applications.
2. ASP.NET Core for Web Development
Dynamic, cross-platform web applications require ASP.NET Core. Learning MVC architecture, dependency injection, and Razor Pages will help you build robust web solutions.
3. Entity Framework Core for Data Access
EF Core simplifies interaction with databases using an object-oriented approach. Developers should be skilled in migrations, LINQ queries, and performance tuning with EF Core.
4. Blazor for Front-End Development
Blazor enables full-stack development with C#, replacing JavaScript in many scenarios. It’s a must-learn for building interactive web UIs with WebAssembly.
5. Cloud Skills with Microsoft Azure
Cloud integration is vital in 2025. Learn to deploy, manage, and scale applications using Azure tools like App Services, Azure Functions, and SQL Azure.
Conclusion
To build a successful .NET development career in 2025, mastering these skills is non-negotiable. But more importantly, you need hands-on experience and expert guidance. For the best .NET training in Hyderabad, choose Monopoly IT Solutions - your trusted partner in building future-ready careers.
0 notes
nathanohn123 · 2 months ago
Text
Mastering ASP.NET: Build Dynamic and Scalable Web Applications
Dive into the world of ASP.NET, a powerful framework for building robust, secure, and scalable web applications. Learn about MVC architecture, Razor Pages, Web APIs, and Blazor, and explore the latest features to enhance your development workflow. Bookmark this for expert insights, tutorials, and best practices! 🚀
Tumblr media
0 notes
inestwebnoida · 8 months ago
Text
Understanding MVC Architecture in ASP.NET
MVC (Model-View-Controller) is a software architectural pattern that divides an application into three main components: Model, View, and Controller. ASP.NET, developed by Microsoft, leverages this architecture to create scalable, maintainable, and testable web applications. In this article, we’ll explore the MVC architecture in ASP.NET, how it works, and why it's a preferred pattern for developers.
What is MVC Architecture?
The MVC architecture separates an application into three interconnected components:
Model: Represents the application’s data and business logic. It directly manages the data and rules of the application, usually interacting with the database in ASP.NET MVC applications.
View: Responsible for displaying the data from the Model to the user. In ASP.NET, Views are typically Razor Pages or HTML markup that dynamically render content based on the data from the Model.
Controller: Acts as a bridge between the Model and View. It handles user requests, processes them (interacting with the Model as necessary), and decides which View to render. In ASP.NET MVC, Controllers are C# classes that manage the flow of data and handle business logic.
How MVC Works in ASP.NET
The request/response cycle in an ASP.NET MVC application follows this pattern:
Routing: The ASP.NET routing engine processes the user’s request and maps it to the correct Controller and action method.
Controller: Receives the request, processes it, and may interact with the Model to retrieve or update data.
Model: Contains the logic for data fetching, updating, or processing.
View: After processing the data, the Controller selects a View, which renders the data and generates an output (typically an HTML page).
Response: The generated View is returned to the user as an HTTP response.
This clear separation ensures that each component focuses on its own responsibilities, resulting in clean and maintainable code.
Key Components of ASP.NET MVC
Models in ASP.NET MVC
Models are responsible for representing the data and business logic of the application. They typically interact with the database, apply validation, and execute business rules. ASP.NET MVC models can use plain C# classes or the Entity Framework for database operations.
Example of a simple Model:
Views in ASP.NET MVC
Views present the data to the user and are generally Razor pages (.cshtml files) that combine HTML and C# code. Razor syntax allows developers to generate dynamic content while maintaining clean code.
Controllers in ASP.NET MVC
Controllers handle user input, processing the data, and determining which View to display. Each action method in a Controller corresponds to a specific endpoint.
Advantages of MVC Architecture in ASP.NET
Separation of Concerns: The business logic (Model), user interface (View), and input logic (Controller) are separated, making the application easier to manage, develop, and test.
Testability: Each component can be independently tested, improving the reliability of the application.
Scalability and Maintainability: As the application grows, features can be added without affecting existing functionality.
Extensibility: ASP.NET MVC is highly extensible, allowing developers to customize components like routing, filters, and dependency injection.
Better Control Over HTML and URLs: MVC gives developers full control over HTML and URLs, essential for building SEO-friendly applications.
MVC in ASP.NET vs. WebForms
Before ASP.NET MVC, developers commonly used WebForms, which followed an event-driven model. While WebForms is easier for beginners, it hides much of the complexity of HTTP, leading to less control over HTML and URLs. MVC, on the other hand, provides full access to underlying web protocols, giving developers more flexibility and control for building modern web applications.
ASP.NET MVC provides a powerful, flexible framework for building web applications with a clear separation of concerns. By leveraging the Model-View-Controller pattern, developers can build scalable, maintainable, and testable applications. Whether for simple websites or complex web applications, ASP.NET MVC offers the tools and structure for success.
For developers transitioning from older frameworks or starting fresh, MVC simplifies development while laying a solid foundation for modern and scalable applications
1 note · View note
faciletechnolab1 · 8 months ago
Text
A Comprehensive Exploration of 10 .NET 8.0 Enhancements Transforming the Blazor Ecosystem
Tumblr media
Dive into the future of web development with our in-depth analysis of 10 .NET 8.0, dissecting the groundbreaking improvements that have revolutionized the Blazor framework, propelling it to new heights of performance and functionality.
The latest release of .NET 8 brings significant additions and changes to ASP.NET Core. The most notable enhancements for this release of ASP.NET Core are related to the Performance and Blazor alongside the updates regarding the AOT, Identity, SignalR, Metrics and many more features.
Microsoft announced that ASP.NET Core in .NET 8 is the most performant released version so far, and as stated, when compared to .NET 7, ASP.NET Core in .NET 8 is 18% faster on the Techempower JSON benchmark and 24% faster on the Fortunes benchmark. Brennan Conroy wrote a blog post about Performance Improvements in ASP.NET Core 8 and readers are recommended to take a look into this.
1. Enhanced Navigation & Form Handling
Say goodbye to clunky page reloads! Blazor now intelligently updates the DOM with server-rendered content, resulting in seamless navigation and form interactions that feel like a native single-page application.
2. Choose Your Render Mode at Runtime
Need more flexibility? .NET 8.0 lets you dynamically switch between server-side and interactive render modes for individual components, giving you granular control over your app's behavior.
3. Streaming Rendering Preserves DOM
Blazor now paints components progressively, preserving existing DOM elements and avoiding unnecessary refreshes. This translates to blazing-fast performance and a more responsive user experience.
4. QuickGrid
Say Hello to Data Tables Made Easy: Forget about writing tons of boilerplate code for data grids. QuickGrid is a new built-in component that handles sorting, filtering, and pagination out of the box, making your life easier and your tables prettier.
5. Improved Authentication
Integrate authentication into your Blazor apps with greater ease thanks to built-in support for OpenID Connect and improved integration with Microsoft Identity Platform.
6. Razor Component Result
Generate static HTML content with your Blazor components! This opens up new possibilities for pre-rendering content and improving SEO.
7. Sections
Modular Layouts Made Simple: Define flexible content areas in your app layout with "Sections" and dynamically fill them with components. This promotes code reuse and keeps your layouts organized.
8. Jiterpreter for Blazor WebAssembly
Get ready for faster Blazor WebAssembly apps! The new Jiterpreter improves component execution speed, making your WebAssembly apps feel native and responsive.
9. Enhanced Routing with Named Elements
Route to specific elements within your Blazor pages using URL fragments, providing finer-grained control over navigation and deep linking.
10. Cascade Query String Values
Pass query string values directly to your Blazor components, simplifying data transmission and making your development workflow more streamlined. Bonus: Blazor Server Interactivity in Web Apps: While still in preview, this feature opens exciting possibilities for running interactive logic on the server for Blazor WebAssembly apps, potentially bridging the gap between the two models.
Ready to get blazing? These are just some of the amazing improvements that await you in .NET 8.0. So, upgrade your projects, explore these new features, and build the next generation of web applications that are fast, dynamic, and simply delightful to use.  
0 notes
scholarhatedu · 1 year ago
Text
0 notes
itonlinetraining · 2 years ago
Text
ASP.NET Core Development
ASP.NET Core Development is a pivotal area of focus for individuals seeking comprehensive dot net training online with certification. This dynamic framework empowers developers to build robust, high-performance web applications that are not only scalable but also platform-agnostic. Enrolling in a dot net online course specialising in ASP.NET Core development is a strategic move for anyone looking to harness the full potential of the .NET ecosystem and stay competitive in the rapidly evolving field of web development.
A well-structured dot net online course dedicated to ASP.NET Core development covers essential topics such as building responsive web applications, leveraging the power of Razor Pages and Blazer components, and harnessing the benefits of the Model-View-Controller (MVC) architectural pattern. These courses often provide hands-on experience, allowing students to master the intricacies of RESTful API design and secure application development. With ASP.NET Core at the forefront, aspiring developers can gain the knowledge and certification needed to excel in the world of modern web development, making them valuable assets in the job market.
Furthermore, ASP.NET Core's cross-platform capabilities make it a versatile choice for developers across various operating systems. A dot net training online with certification in ASP.NET Core Development equips learners with the skills to create dynamic, cloud-ready web applications, ensuring they remain at the forefront of innovation and are well-prepared for the demands of the industry.
0 notes
brainkafe · 2 years ago
Text
Upload File in ASP.Net Core Razor Pages
0 notes
sagar-jaybhay · 5 years ago
Text
Generic List Routing & Routing Constraints
New Post has been published on https://is.gd/e1okJ9
Generic List Routing & Routing Constraints
Tumblr media
In this article we will understand How to display Generic List In Asp.Net Razor Pages? How Routing Works in Asp.Net Razor Pages ? How to apply Routing Constraints in Asp.Net Razor Pages by Sagar Jaybhay.
Generic List Routing & Routing Constraints
Now see below image we need to display employee list like this image. We have Employee property present in our Index page model we access this in our view. Now iterating over this list we apply some bootstrap CSS and formatting to display like below.
Tumblr media
Code in the Display template
@page @model RazorApplication.Pages.Employee.IndexModel @ ViewData["Title"] = "Employees"; <h1>Employees</h1> <h3>No of Employees : @Model.Employees.Count()</h3> <hr /> <br /> <div class="container-fluid"> @foreach (var emp in Model.Employees) var imgSrc = @"images/" + (emp.Photopath.Trim().Length != 0 ? emp.Photopath : "noimage.png"); <div class="row" style="border:thin 1px black"> <div class="col-lg-4"> <img src="@imgSrc" alt="@emp.Name" style="height:150px;width:150px" /> </div> <div class="col-lg-4"> <table style="border:thin;1px" class="table table-bordered table-active"> <tbody> <tr> <td>Name</td> <td>@emp.Name</td> </tr> <tr> <td>Email</td> <td>@emp.Email</td> </tr> <tr> <td>Department</td> <td>@emp.Dept</td> </tr> </tbody> </table> </div> <div class="col-lg-2"> <table class="table table-bordered"> <tbody> <tr><td><a href="#" class="btn btn-info">Edit</a></td></tr> <tr><td><a href="#" class="btn btn-primary">View</a></td></tr> <tr><td><a href="#" class="btn btn-danger">Delete</a></td></tr> </tbody> </table> </div> </div> <hr /> <br /> </div>
Tumblr media
See the above image in that we use this Employees Property in our Index.cshtml Display template.
Tumblr media
Basics Of Routing In Asp.Net Razor Pages:
Routing is the URL pattern matching techniques and in this, it matches URLs with razor Pages. It is like most of page centric frameworks where URLs match with physical file paths. Keypoint to remember it start with the Root folder and in this Pages is the root folder.
Like MVC Razor pages also use Conventions and Configuration for routing. Razor pages use the same infrastructure as MVC for routing.
The standard Razor Pages 3.x site template includes 3 pages in the root folder.
Error.cshtml
Index.cshtml
Privacy.cshtml
By default, route templates are generated by taking the root path of each Content Page and then it removes root folder name from the start of path and extension from the end of the path.
In Asp.Net Razor pages Index.cshtml is the default document present in any folder so it has 2 different routes one with “blank and other with https://sagarjaybhay.com/index
So in our application, we created the Employee folder and in that we Index.cshtml so our route becomes
“blank which is an empty string path is “https://yourdomain.com/Employee”
“Employee/Index” this is the second path https://yourdomain.com/Employee/index
But if you create Employee.cshtml in your root domain and Employee folder is present in your Pages folder then when you run your application it will throw an exception.
An unhandled exception occurred while processing the request.
AmbiguousMatchException: The request matched multiple endpoints. Matches: /Employee /Employee/Index
Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ReportAmbiguity(CandidateState[] candidateState)
Tumblr media
How to handle this AmbigousMatch Exception in Asp.Net Razor pages?
One to overcome this error by renaming one of the file or folder names in our Asp.net razor page application.
The second way is to Overwrite default routes. We know that if Routes in Asp.Net razor pages are mapped to a physical file location.
@page "EmployeeList"
We are giving above custom route names to our page in Employee folders Index.cshtml file and error is gone see below image
Tumblr media
So by giving this custom route, you can’t use the default route in our application means  https://yourdomain.com/Employee/Index this route won’t work.
The third way to overcome this error is used Route parameter in our application
@page "name"
In the above we give name is our route parameter and when we invoke the URL
https://yourdomain.com/Employee/abc here ABC is our route parameter.
Tumblr media
Constraint on Route Parameter
If we see above URL we pass ABC to name parameter in Index view which can accept any value like character, number any value to add a constraint. Now we want our URL parameter to accept the only character then we have name:constraint_name syntax.
@page "name:alpha"
By doing this our URL only accepts the character and if we pass number it will throw an error.
Tumblr media Tumblr media
GitHub:- https://github.com/Sagar-Jaybhay/AspNerRazorPages
1 note · View note
ryadel · 2 years ago
Link
2 notes · View notes
monopolytraininginstitute · 2 months ago
Text
The Power of .NET : A Complete Guide to Modern Software Development
Introduction
.NET is a leading framework for building secure, scalable, and high-performance applications. Whether you're developing web, desktop, or cloud-based applications, .NET provides a flexible and efficient environment for software development. If you’re searching for the best dot.net training institute in Hyderabad, it’s crucial to choose one that offers hands-on learning and real-world applications.
What is .NET?
.NET is an open-source, cross-platform framework developed by Microsoft, supporting multiple programming languages like C#, F#, and VB.NET. Its powerful ecosystem enables developers to build a wide variety of applications, from enterprise solutions to web and mobile apps.
Key Features of .NET
1. Cross-Platform Support
With .NET Core, developers can create applications that run seamlessly on Windows, macOS, and Linux, making it a versatile choice for modern development.
2. High Performance and Scalability
The framework’s Just-In-Time (JIT) compilation, garbage collection, and optimized runtime ensure superior performance and resource management, ideal for large-scale applications.
3. Object-Oriented Approach
.NET supports object-oriented programming (OOP), improving code organization, reusability, and maintainability, leading to efficient and scalable development.
4. Feature-Rich Development Environment
Microsoft’s Visual Studio provides an advanced Integrated Development Environment (IDE) with debugging tools, version control, and cloud integration, making development seamless.
5. Robust Security Mechanisms
.NET ensures security through authentication, authorization, encryption, and built-in identity management features, making it a reliable choice for enterprise applications.
6. Web Application Development
ASP.NET, a part of the .NET framework, is widely used for developing powerful and dynamic web applications using MVC architecture, Razor Pages, and Web APIs.
7. Cloud and Microservices Support
.NET allows developers to build and deploy microservices-based applications efficiently, ensuring scalability and performance in cloud computing environments.
Why Choose .NET?
Industry Relevance
Major enterprises rely on .NET for mission-critical applications, creating high demand for skilled .NET developers in various industries.
Multi-Purpose Framework
From gaming to enterprise software, cloud solutions to mobile applications, .NET serves as an all-in-one framework for diverse development needs.
Strong Community and Microsoft Backing
With an active developer community, extensive documentation, and continuous updates, .NET remains a future-proof technology for developers.
Best Practices for .NET Development
Implement Dependency Injection (DI) for modular and maintainable code.
Use Asynchronous Programming with async/await to improve application responsiveness.
Follow SOLID Principles to ensure clean and scalable code.
Optimize database interactions using Entity Framework (EF) Core.
Enhance security by implementing Authentication and Authorization best practices.
How to Learn .NET Effectively
Beginners should start by learning C# basics before diving into ASP.NET and .NET Core. Engaging in real-world projects, online courses, and interactive coding sessions will accelerate learning.
For structured guidance, choosing the best dot.net training institute in Hyderabad is essential. Look for a course that covers hands-on projects, industry exposure, and expert mentorship.
Conclusion
.NET continues to dominate software development, offering efficiency, security, and flexibility. Whether you’re a beginner or an experienced developer, mastering .NET can unlock exciting career opportunities. To gain hands-on expertise, consider enrolling in a professional training program. Monopoly IT Solutions provides industry-oriented .NET training, equipping learners with the practical skills needed to succeed in the tech industry.
0 notes
aegisisc · 3 years ago
Link
.NET Core 2.0 is all about making things easier. It just made simpler to get started with developing web apps along with building great rich UI.  Razor pages are one of its newly introduced feature. Razor pages works with .NET Core 2.0 or higher and are only supported by Visual Studio 2017 v 15.3 or later only.
0 notes
mattn · 6 years ago
Text
.NET Core 3.0 が gRPC をサポートした。
「.NET Core 3.0」正式版が登場。Windowsデスクトップアプリ開発可能、exeファイルを生成、マイクロサービス対応など - Publickey
最新記事10本 Kafka開発元のConfluentに聞いた。エンタープライズ市場への道筋、大手クラウドとの現在の関係について 最大32コアのAMD EPYCプロセッサを搭載、コストパフォーマンスを高...
https://ift.tt/2mg6uiV
これまで通り、dotnet コマンドで SDK テンプレートを使って色々なアプリケーションを作成できる様になっている。dotnet 3.0 から使える SDK テンプレートは以下の通り。
使用法: new [options] オプション:   -h, --help          Displays help for this command.   -l, --list          Lists templates containing the specified name. If no name is specified, lists all templates.   -n, --name          The name for the output being created. If no name is specified, the name of the current directory is used.   -o, --output        Location to place the generated output.   -i, --install       Installs a source or a template pack.   -u, --uninstall     Uninstalls a source or a template pack.   --nuget-source      Specifies a NuGet source to use during install.   --type              Filters templates based on available types. Predefined values are "project", "item" or "other".   --dry-run           Displays a summary of what would happen if the given command line were run if it would result in a template creation.   --force             Forces content to be generated even if it would change existing files.   -lang, --language   Filters templates based on language and specifies the language of the template to create.   --update-check      Check the currently installed template packs for updates.   --update-apply      Check the currently installed template packs for update, and install the updates. Templates                                         Short Name               Language          Tags                                  ---------------------------------------------------------------------------------------------------------------------------------- Console Application                               console                  [C#], F#, VB      Common/Console                        Class library                                     classlib                 [C#], F#, VB      Common/Library                        WPF Application                                   wpf                      [C#]              Common/WPF                            WPF Class library                                 wpflib                   [C#]              Common/WPF                            WPF Custom Control Library                        wpfcustomcontrollib      [C#]              Common/WPF                            WPF User Control Library                          wpfusercontrollib        [C#]              Common/WPF                            Windows Forms (WinForms) Application              winforms                 [C#]              Common/WinForms                       Windows Forms (WinForms) Class library            winformslib              [C#]              Common/WinForms                       Worker Service                                    worker                   [C#]              Common/Worker/Web                     Unit Test Project                                 mstest                   [C#], F#, VB      Test/MSTest                           NUnit 3 Test Project                              nunit                    [C#], F#, VB      Test/NUnit                            NUnit 3 Test Item                                 nunit-test               [C#], F#, VB      Test/NUnit                            xUnit Test Project                                xunit                    [C#], F#, VB      Test/xUnit                            Razor Component                                   razorcomponent           [C#]              Web/ASP.NET                           Razor Page                                        page                     [C#]              Web/ASP.NET                           MVC ViewImports                                   viewimports              [C#]              Web/ASP.NET                           MVC ViewStart                                     viewstart                [C#]              Web/ASP.NET                           Blazor Server App                                 blazorserver             [C#]              Web/Blazor                            ASP.NET Core Empty                                web                      [C#], F#          Web/Empty                             ASP.NET Core Web App (Model-View-Controller)      mvc                      [C#], F#          Web/MVC                               ASP.NET Core Web App                              webapp                   [C#]              Web/MVC/Razor Pages                   ASP.NET Core with Angular                         angular                  [C#]              Web/MVC/SPA                           ASP.NET Core with React.js                        react                    [C#]              Web/MVC/SPA                           ASP.NET Core with React.js and Redux              reactredux               [C#]              Web/MVC/SPA                           Razor Class Library                               razorclasslib            [C#]              Web/Razor/Library/Razor Class Library ASP.NET Core Web API                              webapi                   [C#], F#          Web/WebAPI                            ASP.NET Core gRPC Service                         grpc                     [C#]              Web/gRPC                              dotnet gitignore file                             gitignore                                  Config                                global.json file                                  globaljson                                 Config                                NuGet Config                                      nugetconfig                                Config                                Dotnet local tool manifest file                   tool-manifest                              Config                                Web Config                                        webconfig                                  Config                                Solution File                                     sln                                        Solution                              Protocol Buffer File                              proto                                      Web/gRPC                              Examples:     dotnet new mvc --auth Individual     dotnet new --help
WinForms や WPF を使ったアプリケーションの開発もできる。すばらしい。
dotnet 3.0 で WinForms なアプリ動いた。 pic.twitter.com/46TkkM47SP
— mattn (@mattn_jp) September 24, 2019
以下の手順でアプリケーションを作成すると、SayHello というメソッドを持った Greeter サービスが作られる。
$ dotnet new grpc -o mygrpc
proto ファイルは以下の通り。
syntax = "proto3"; option csharp_namespace = "mygrpc"; package Greet; // The greeting service definition. service Greeter {   // Sends a greeting   rpc SayHello (HelloRequest) returns (HelloReply); } // The request message containing the user's name. message HelloRequest {   string name = 1; } // The response message containing the greetings. message HelloReply {   string message = 1; }
dotnet コマンドを使ってそのまま実行できる。
試しにこの proto ファイルから Go のクライアントを作って接続してみる。以下のコマンドで Go のクライアントが作られる。
$ go get github.com/golang/protobuf/protoc-gen-go $ protoc --go_out=plugins=grpc:. greet.proto
以下がそのクライアントを使ったサンプル。dotnet のサーバ側はポート 5000 番で通常ソケットの HTTP、5001 番で HTTP/2 で通信可能。dotnet run コマンドでは HTTP 通信のサーバは起動しないので dotnet build でビルドし、bin 配下にある exe ファイルを実行する。この exe ファイル出力も今回の .NET Core 3.0 の新しい機能になる。
package main import (     "fmt"     "log"     pb "github.com/mattn/grpc-greeter/Greet"     "golang.org/x/net/context"     "google.golang.org/grpc" ) func main() {     conn, err := grpc.Dial("127.0.0.1:5000", grpc.WithInsecure())     if err != nil {         log.Fatal(err)     }     /*         opts = append(opts, grpc.WithTransportCredentials(creds))     */     defer conn.Close()     client := pb.NewGreeterClient(conn)     hello := &pb.HelloRequest{         Name: "おるみん",     }     result, err := client.SayHello(context.Background(), hello)     if err != nil {         log.Fatal(err)     }     fmt.Println(result.GetMessage()) }
実行すると以下の結果が得られる。
Hello おるみん
from Big Sky https://ift.tt/2msTsz2
1 note · View note
nunthu · 6 years ago
Link
1 note · View note