Call windows service from browser

Use gRPC in browser apps

Learn how to configure an existing ASP.NET Core gRPC service to be callable from browser apps, using the gRPC-Web protocol. gRPC-Web allows browser JavaScript and Blazor apps to call gRPC services. It’s not possible to call an HTTP/2 gRPC service from a browser-based app. gRPC services hosted in ASP.NET Core can be configured to support gRPC-Web alongside HTTP/2 gRPC.

For instructions on adding a gRPC service to an existing ASP.NET Core app, see Add gRPC services to an ASP.NET Core app.

gRPC-Web in ASP.NET Core vs. Envoy

There are two choices for how to add gRPC-Web to an ASP.NET Core app:

  • Support gRPC-Web alongside gRPC HTTP/2 in ASP.NET Core. This option uses middleware provided by the Grpc.AspNetCore.Web package.
  • Use the Envoy proxy’s gRPC-Web support to translate gRPC-Web to gRPC HTTP/2. The translated call is then forwarded onto the ASP.NET Core app.

There are pros and cons to each approach. If an app’s environment is already using Envoy as a proxy, it might make sense to also use Envoy to provide gRPC-Web support. For a basic solution for gRPC-Web that only requires ASP.NET Core, Grpc.AspNetCore.Web is a good choice.

Configure gRPC-Web in ASP.NET Core

gRPC services hosted in ASP.NET Core can be configured to support gRPC-Web alongside HTTP/2 gRPC. gRPC-Web does not require any changes to services. The only modification is startup configuration.

To enable gRPC-Web with an ASP.NET Core gRPC service:

  • Add a reference to the Grpc.AspNetCore.Web package.
  • Configure the app to use gRPC-Web by adding UseGrpcWeb and EnableGrpcWeb to Startup.cs:

The preceding code:

  • Adds the gRPC-Web middleware, UseGrpcWeb , after routing and before endpoints.
  • Specifies the endpoints.MapGrpcService () method supports gRPC-Web with EnableGrpcWeb .

Alternatively, the gRPC-Web middleware can be configured so all services support gRPC-Web by default and EnableGrpcWeb isn’t required. Specify new GrpcWebOptions < DefaultEnabled = true >when the middleware is added.

There is a known issue that causes gRPC-Web to fail when hosted by HTTP.sys in .NET Core 3.x.

A workaround to get gRPC-Web working on HTTP.sys is available here.

gRPC-Web and CORS

Browser security prevents a web page from making requests to a different domain than the one that served the web page. This restriction applies to making gRPC-Web calls with browser apps. For example, a browser app served by https://www.contoso.com is blocked from calling gRPC-Web services hosted on https://services.contoso.com . Cross Origin Resource Sharing (CORS) can be used to relax this restriction.

To allow a browser app to make cross-origin gRPC-Web calls, set up CORS in ASP.NET Core. Use the built-in CORS support, and expose gRPC-specific headers with WithExposedHeaders.

The preceding code:

  • Calls AddCors to add CORS services and configures a CORS policy that exposes gRPC-specific headers.
  • Calls UseCors to add the CORS middleware after routing and before endpoints.
  • Specifies the endpoints.MapGrpcService () method supports CORS with RequiresCors .

gRPC-Web and streaming

Traditional gRPC over HTTP/2 supports streaming in all directions. gRPC-Web offers limited support for streaming:

  • gRPC-Web browser clients don’t support calling client streaming and bidirectional streaming methods.
  • ASP.NET Core gRPC services hosted on Azure App Service and IIS don’t support bidirectional streaming.

When using gRPC-Web, we only recommend the use of unary methods and server streaming methods.

Call gRPC-Web from the browser

Browser apps can use gRPC-Web to call gRPC services. There are some requirements and limitations when calling gRPC services with gRPC-Web from the browser:

  • The server must have been configured to support gRPC-Web.
  • Client streaming and bidirectional streaming calls aren’t supported. Server streaming is supported.
  • Calling gRPC services on a different domain requires CORS to be configured on the server.
Читайте также:  Что такое linux kernel api

JavaScript gRPC-Web client

There is a JavaScript gRPC-Web client. For instructions on how to use gRPC-Web from JavaScript, see write JavaScript client code with gRPC-Web.

Configure gRPC-Web with the .NET gRPC client

The .NET gRPC client can be configured to make gRPC-Web calls. This is useful for Blazor WebAssembly apps, which are hosted in the browser and have the same HTTP limitations of JavaScript code. Calling gRPC-Web with a .NET client is the same as HTTP/2 gRPC. The only modification is how the channel is created.

  • Add a reference to the Grpc.Net.Client.Web package.
  • Ensure the reference to Grpc.Net.Client package is 2.29.0 or greater.
  • Configure the channel to use the GrpcWebHandler :

The preceding code:

  • Configures a channel to use gRPC-Web.
  • Creates a client and makes a call using the channel.

GrpcWebHandler has the following configuration options:

  • InnerHandler: The underlying HttpMessageHandler that makes the gRPC HTTP request, for example, HttpClientHandler .
  • GrpcWebMode: An enumeration type that specifies whether the gRPC HTTP request Content-Type is application/grpc-web or application/grpc-web-text .
    • GrpcWebMode.GrpcWeb configures content to be sent without encoding. Default value.
    • GrpcWebMode.GrpcWebText configures content to be base64 encoded. Required for server streaming calls in browsers.
  • HttpVersion: HTTP protocol Version used to set HttpRequestMessage.Version on the underlying gRPC HTTP request. gRPC-Web doesn’t require a specific version and doesn’t override the default unless specified.

Generated gRPC clients have sync and async methods for calling unary methods. For example, SayHello is sync and SayHelloAsync is async. Calling a sync method in a Blazor WebAssembly app will cause the app to become unresponsive. Async methods must always be used in Blazor WebAssembly.

Use gRPC client factory with gRPC-Web

A gRPC-Web compatible .NET client can be created using the gRPC client factory.

Доступ к службе из веб-браузера (краткое руководство по службе данных WCF) Accessing the Service from a Web Browser (WCF Data Services Quickstart)

Службы данных WCF является устаревшим и больше не будет доступен для скачивания из центра загрузки Майкрософт. WCF Data Services has been deprecated and will no longer be available for download from the Microsoft Download Center. Службы данных WCF поддерживали только более ранние версии протокола Microsoft OData (v1-v3) и не были активны в рамках активной разработки. WCF Data Services supported earlier versions of the Microsoft OData (V1-V3) protocol only and has not been under active development. OData v1-v3 заменена OData версии 4, которая является отраслевым стандартом, опубликованным OASIS и ратифицирован по ISO. OData V1-V3 has been superseded by OData V4, which is an industry standard published by OASIS and ratified by ISO. OData v4 поддерживается в базовых библиотеках, совместимых с OData V4, доступных в Microsoft. OData. Core. OData V4 is supported through the OData V4 compliant core libraries available at Microsoft.OData.Core. Документация по поддержке доступна по адресу OData.NET, а библиотеки служб OData v4 доступны в Microsoft. AspNetCore. OData. Support documentation is available at OData.Net, and the OData V4 service libraries are available at Microsoft.AspNetCore.OData.

Рестиер — это последующий службы данных WCF. RESTier is the successor to WCF Data Services. Рестиер помогает в минутах запрашивать стандартизированный, поддерживающий запросы интерфейс RESTFUL на основе HTTP. RESTier helps you bootstrap a standardized, queryable, HTTP-based REST interface in minutes. Как и службы данных WCF, Рестиер предоставляет простые и понятные способы формирования запросов и перехвата отправок до и после попадания в базу данных. Like WCF Data Services before it, Restier provides simple and straightforward ways to shape queries and intercept submissions before and after they hit the database. И, как и веб-API + OData, у вас по-прежнему есть гибкость в добавлении собственных настраиваемых запросов и действий с помощью уже знакомых методов. And like Web API + OData, you still have the flexibility to add your own custom queries and actions with techniques you’re already familiar with.

Читайте также:  Постоянно запускается установщик windows

Это вторая задача краткого руководства по службы данных WCF. This is the second task of the WCF Data Services quickstart. В этой задаче вы запускаете службы данных WCF из Visual Studio и при необходимости отключаете чтение веб-канала в браузере. In this task, you start the WCF Data Services from Visual Studio and optionally disable feed reading in the Web browser. Затем вы получаете документ определения службы и доступ к ресурсам службы данных, отправляя запросы HTTP GET через веб-браузер к предоставленным ресурсам. You then retrieve the service definition document as well as access data service resources by submitting HTTP GET requests through a Web browser to the exposed resources.

По умолчанию Visual Studio автоматически приписывает для URI на компьютере номер порта localhost . By default, Visual Studio auto-assigns a port number to the localhost URI on your computer. В данной задаче в примерах URI используется порт номер 12345 . This task uses the port number 12345 in the URI examples. Дополнительные сведения о том, как задать конкретный номер порта в проекте Visual Studio, см. в разделе Создание службы данных. For more information about how to set a specific port number in your Visual Studio project see Creating the Data Service.

Запрос сервисного документа по умолчанию с помощью Internet Explorer To request the default service document by using Internet Explorer

В Internet Explorer в меню Сервис выберите Свойства обозревателя, перейдите на вкладку содержимое , щелкните Параметры и снимите флажок включить просмотр веб-канала. In Internet Explorer, from the Tools menu, select Internet Options, click the Content tab, click Settings, and clear Turn on feed viewing.

При этом чтение каналов будет отключено. This makes sure that feed reading is disabled. Если не выключить эту функцию, то веб-браузер будет рассматривать документ в формате AtomPub в качестве канала XML, а не отображать необработанные данные XML. If you do not disable this functionality, then the Web browser will treat the returned AtomPub encoded document as an XML feed instead of displaying the raw XML data.

Если браузер не может отобразить канал в виде необработанных XML-данных, его все равно можно просмотреть в виде исходного кода страницы. If your browser cannot display the feed as raw XML data, you should still be able to view the feed as the source code for the page.

В Visual Studio нажмите клавишу F5 , чтобы начать отладку приложения. In Visual Studio, press the F5 key to start debugging the application.

Откройте веб-браузер на локальном компьютере. Open a Web browser on the local computer. В адресной строке введите следующий URI: In the address bar, enter the following URI:

При этом будет возвращен сервисный документ по умолчанию, в котором содержится список наборов сущностей, предоставляемых службой данных. This returns the default service document, which contains a list of entity sets that are exposed by this data service.

Доступ к ресурсам набора сущностей из веб-браузера To access entity set resources from a Web browser

В адресной строке веб-браузера введите следующий URI: In the address bar of your Web browser, enter the following URI:

При этом будет возвращен набор всех клиентов из образца базы данных Northwind. This returns a set of all customers in the Northwind sample database.

В адресной строке веб-браузера введите следующий URI: In the address bar of your Web browser, enter the following URI:

При этом возвращается экземпляр сущности для конкретного клиента ALFKI . This returns an entity instance for the specific customer, ALFKI .

В адресной строке веб-браузера введите следующий URI: In the address bar of your Web browser, enter the following URI:

При этом произойдет переход по связи между клиентами и заказами для возвращения набора всех заказов для конкретного клиента ALFKI . This traverses the relationship between customers and orders to return a set of all orders for the specific customer ALFKI .

В адресной строке веб-браузера введите следующий URI: In the address bar of your Web browser, enter the following URI:

При этом будут отфильтрованы заказы, принадлежащие конкретному клиенту ALFKI , в результате чего будет возвращен только конкретный заказ на основе переданного значения OrderID . This filters orders that belong to the specific customer ALFKI so that only a specific order is returned based on the supplied OrderID value.

Читайте также:  Dotnetfx для windows 10

Next Steps Next Steps

Вы успешно получили доступ к службы данных WCF из веб-браузера, где браузер выдает HTTP-запросы GET к указанным ресурсам. You have successfully accessed the WCF Data Services from a Web browser, with the browser issuing HTTP GET requests to specified resources. Веб-браузер предоставляет простой способ проведения экспериментов с синтаксисом адресации запросов и просмотра результатов. A Web browser provides an easy way to experiment with the addressing syntax of requests and view the results. Однако к производственной службе данных таким способом обычно не обращаются. However, a production data service is not generally accessed by this method. Как правило, взаимодействие приложений со службой данных осуществляется через программный код или языки сценариев. Typically, applications interact with the data service through application code or scripting languages. Далее мы создадим клиентское приложение, которое использует клиентские библиотеки для обращения к ресурсам службы данных, как если бы они являлись объектами CLR. Next, you will create a client application that uses client libraries to access data service resources as if they were common language runtime (CLR) objects:

A new experiment: Call .NET gRPC services from the browser with gRPC-Web

I’m excited to announce experimental support for gRPC-Web with .NET. gRPC-Web allows gRPC to be called from browser-based apps like JavaScript SPAs or Blazor WebAssembly apps.

gRPC-Web for .NET promises to bring many of gRPC’s great features to browser apps:

  • Strongly-typed code-generated clients
  • Compact Protobuf messages
  • Server streaming

What is gRPC-Web

It is impossible to implement the gRPC HTTP/2 spec in the browser because there is no browser API with enough fine-grained control over HTTP requests. gRPC-Web solves this problem by being compatible with HTTP/1.1 and HTTP/2.

gRPC-Web is not a new technology. There is a stable gRPC-Web JavaScript client, and a proxy for translating between gRPC and gRPC-Web for services. The new experimental packages allow an ASP.NET Core gRPC app to support gRPC-Web without a proxy, and allow the .NET Core gRPC client to call gRPC-Web services. (great for Blazor WebAssembly apps!)

New opportunites with gRPC-Web

  • Call ASP.NET Core gRPC apps from the browser – Browser APIs can’t call gRPC HTTP/2. gRPC-Web offers a compatible alternative.
    • JavaScript SPAs
    • .NET Blazor Web Assembly apps
  • Host ASP.NET Core gRPC apps in IIS and Azure App Service – Some servers, such as IIS and Azure App Service, currently can’t host gRPC services. While this is actively being worked on, gRPC-Web offers an interesting alternative that works in every environment today.
  • Call gRPC from non-.NET Core platforms – Some .NET platforms HttpClient doesn’t support HTTP/2. gRPC-Web can be used to call gRPC services on these platforms (e.g. Blazor WebAssembly, Xamarin).

Note that there is a small performance cost to gRPC-Web, and two gRPC features are no longer supported: client streaming and bi-directional streaming. (server streaming is still supported!)

Server gRPC-Web instructions

If you are new to gRPC in .NET, there is a simple tutorial to get you started.

gRPC-Web does not require any changes to your services, the only modification is startup configuration. To enable gRPC-Web with an ASP.NET Core gRPC service, add a reference to the Grpc.AspNetCore.Web package. Configure the app to use gRPC-Web by adding AddGrpcWeb(. ) and UseGrpcWeb() in the startup file: Startup.cs

Some additional configuration may be required to call gRPC-Web from the browser, such as configuring the app to support CORS.

Client gRPC-Web instructions

The JavaScript gRPC-Web client has instructions for setting up a gRPC-Web client to use in browser JavaScript SPAs.

Calling gRPC-Web with a .NET client is the same as regular gRPC, the only modification is how the channel is created. To enable gRPC-Web, add a reference to the Grpc.Net.Client.Web package. Configure the channel to use the GrpcWebHandler :

To see gRPC-Web with .NET in action, take a moment to read a great blog post written by Steve Sanderson that uses gRPC-Web in Blazor WebAssembly.

Оцените статью