How to fix "err connection refused" in angular - c#

I am building an web application with webApi and angular 7 .
The webApi part works because when I run dotnet watch run it brings my data from the database in the browser but when I connect it with angular I get err connection refused.
I checked the url. It is correct
This is my service.ts :
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
const apiUrl = 'http://localhost:5000/api';
#Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error("emptyyyyyy"); // log to console instead
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
getEmployees(): Observable<Employee[]> {
return this.http.get<Employee[]>(apiUrl)
.pipe(
catchError(this.handleError('getSuppliers', []))
);
}
}
In the console it sayss : emptyyy and err connection refused

Related

How can I call gRPC endpoint from Next.js Application inside of a functional component?

I have set up default gRPC server via Visual Studio .net 6.0.
The proto file is as foolowing:
syntax = "proto3";
option csharp_namespace = "GrpcService";
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;
}
And the Greeter service as following:
using Grpc.Core;
namespace GrpcService.Services
{
public class GreeterService : Greeter.GreeterBase
{
private readonly ILogger<GreeterService> _logger;
public GreeterService(ILogger<GreeterService> logger)
{
_logger = logger;
}
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
return Task.FromResult(new HelloReply
{
Message = "Hello " + request.Name
});
}
}
}
So the default one, nothing fancy. I know how to call this service via C#. And I get back the result as per the function above.
I though don't understand what packages and how should I call it from a web app client via javascript, in a next.js component.
I want to achieve that on a click [for example] I will be calling this.
import type { NextPage } from "next";
import styles from "../styles/Home.module.css";
const Home: NextPage = () => {
const grpcCall = () => {
try {
const grpc = require("grpc");
const protoLoader = require("#grpc/proto-loader");
const packageDef = protoLoader.loadSync("greet.proto", {});
const grpcObject = grpc.loadPackageDefinition(packageDef);
const greetPackage = grpcObject.greet;
const client = new greetPackage.Greeter(
"https://localhost:49153/",
grpc.credentials.createInsecure()
);
client.SayHello({ name: "Say Hello" });
} catch (error) {
console.log(error);
}
};
return (
<div className={styles.container}>
<div onClick={grpcCall} className={styles.title}>
Press to call gRPC HERE
</div>
</div>
);
};
export default Home;
The above code though complains about fs not being resolved, though I don't really think it is the issue.
Error:
Module not found: Can't resolve 'fs'
Import trace for requested module:
./node_modules/#grpc/proto-loader/build/src/index.js
./pages/index.tsx
https://nextjs.org/docs/messages/module-not-found
Could not find files for / in .next/build-manifest.json
Could not find files for / in .next/build-manifest.json
And the whole project is a default next.js app with typescript setting.
So the question is How do I do the call from a javascript client to C# server via gRPC? What code should I add here?
I would apprieciete a simple solution here and if possible detailed explanation.
Regards,

How to use webSocketOptions.AllowedOrigins?

I have an ASP web app.
The app opens a websocket communication server. The websocket server works properly.
var webSocketOptions = new WebSocketOptions()
{
KeepAliveInterval = TimeSpan.FromSeconds(120),
};
app.UseWebSockets(webSocketOptions);
app.Use(async (context, next) =>
{
if (context.Request.Path == "/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
using (WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync())
{
//do some stuff
}
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
When I open my domain example.com and go to Chrome Web Console, the following code works :
var socket = new WebSocket("wss://www.example.com/ws");
However when I add the security constraint :
webSocketOptions.AllowedOrigins.Add("https://www.example.com");
The websocket connection doesn't work anymore. I'm getting the error
VM376:1 WebSocket connection to 'wss://www.example.com/ws' failed: Error during WebSocket handshake: Unexpected response code: 403
Can anyone help please on how to use webSocketOptions.AllowedOrigins ?
I want the Websocket access be allowed only when a request is made from my website www.example.com
Thanks
You have to configure "webSocketOptions.AllowedOrigins" inside your startup middleWare
here a microsoft websocket doc:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/websockets?view=aspnetcore-3.1

Signal R Server Client "Access-Control-Allow-Origin" missing error

I'm trying out the Signal R and built a server dll (windows service library/c#) that runs as a Windows Services. I have build also a client application (asp.net web application) to communicate with the server.
But i'm getting always the error(Firefox) "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%5D&_=1482829095207. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."
Chrome error "
Failed to load resource: the server responded with a status of 400 (Bad Request)"
XMLHttpRequest cannot load http://localhost:8080/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%5D&_=1482830200155. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50259' is therefore not allowed access. The response had HTTP status code 400.
Note: Edge and also IE gives me errors
I have read almost every post about this subject on Stackoverflow, but non of these solutions seems to work.
The code i'm using for the server side:
namespace SignalRService
{
public class StartupConfiguration
{
public void Configuration(IAppBuilder app)
{
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true,
EnableJSONP = true,
};
map.RunSignalR(hubConfiguration);
});
}
}
}
Services.cs
public void StartService()
{
LogMessage("SignalRService started", true);
Running = true;
WebApp.Start<StartupConfiguration>(ConfigurationManager.AppSettings["SignalRServerUrl"]);
}
EnvironmentSettings.config:
<add key="SignalRServerUrl" value="http://localhost:8080"/>
Hubs.cs
namespace SignalRService.Hubs
{
[HubName("TestHub")]
public class TestHub: Hub
{
public static Dictionary<string, List<HubClient>> clients = new Dictionary<string, List<HubClient>>();
[HubMethodName("Subscribe")]
public async Task Subscribe(string Id)
{...... }}
ClientSide (Javascript/Jquery)
var signalrHubConnection;
var signalrHubConnectionProxy;
var signalRServerUrl = "http://localhost:8080";
var currentTimeout;
var count = 0;
var startSignalRConnection = function () {
console.log("Start");
signalrHubConnection = $.hubConnection(signalRServerUrl);
console.log("Running");
signalrHubConnection.logging = true;
signalrHubConnectionProxy = signalrHubConnection.createHubProxy('TestHub');
console.log("--Subscribe starting");
signalrHubConnection.start()
.done(function () {
signalrHubConnectionProxy.invoke('Subscribe', Id.toString());
console.log("Subscribe ending");
})
.fail(function (test) {
if (count < 5) {
console.log(test.toString());
clearTimeout(currentTimeout);
currentTimeout = setTimeout(function () {
count++;
startSignalRConnection();
}, 300000); // retry after 5 minutes
}
}
);
signalrHubConnectionProxy.on('IncomingMessage',
function (message) {
console.log("Message = " + message.toString());
}
);
};
Test.aspx
<script src="https://code.jquery.com/jquery-3.1.1.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/signalr/jquery.signalr-2.2.1.min.js"></script>
Did I something wrong?
The error implied that the SignalR url is different from the requesting url (origin). So, SignalR is on localhost, but your main website (the site that holds the client side example) obviously is accessed using "localhost".
Maybe you're accessing it using an IP (eg http://127.0.0.1/) or your PC name (eg http://badassPC/), whereas they must match under the default SignalR setting. I am pretty certain it doesn't matter if the port is different, and also doesn't matter if they are on the same domain (eg www.mysite.com and signalr.mysite.com)
Note there is a workaround that I wouldn't recommend unless you really really know what you're doing as there is a quite serious security risk otherwise: https://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#crossdomain

SignalR negotiate succesfully but fail at start request

I am developing a chat application for our internal application using SignalR in a javascript angularJS client with a (self hosted for the moment) webAPI. This is in a cross domain connection.
using SignalR 2.2.1
using Owin 3.0.1
using Angular 1.5.7 if that's relevant
My problem is whenever I try to establish a connexion with my hub,
[08:26:38 GMT-0400 (Est (heure d’été))] SignalR: Auto detected cross domain url.jquery.signalR.js:82
[08:26:38 GMT-0400 (Est (heure d’été))] SignalR: Client subscribed to hub 'chathub'.jquery.signalR.js:82
[08:26:38 GMT-0400 (Est (heure d’été))] SignalR: Negotiating with 'https: localhost:44361/signalr/negotiateclientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D'.jquery.signalR.js:82
[08:26:38 GMT-0400 (Est (heure d’été))] SignalR: webSockets transport starting.jquery.signalR.js:82
[08:26:38 GMT-0400 (Est (heure d’été))] SignalR: Connecting to websocket endpoint 'wss: localhost:44361/signalr/connect?transport=webSockets&clientProtocol=1…kAIY9w9Q%3D%3D&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&tid=4'.jquery.signalR.js:82
[08:26:38 GMT-0400 (Est (heure d’été))] SignalR: Websocket opened.
the start request fails
[08:26:38 GMT-0400 (Est (heure d’été))] SignalR: webSockets transport connected. Initiating start request.
Failed to load resource: the server responded with a status of 500 ()
XMLHttpRequest cannot load https: localhost:44361/signalr/start?transport=webSockets&clientProtocol=1…D%3D&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&_=1471436795468. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https: localhost:3000' is therefore not allowed access. The response had HTTP status code 500.
I've tried to pin point this problem for a couple of days now and what've noticed is that in the start request call, the response is missing the 'Access-Control-Allow-Origin' header. What bugs me most is that the negotiate request and the abort request both contains the header
Negotiate Request
Request URL:https: localhost:44361/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&_=14714 39245326
Request Method:GET
Status Code:200 OK
Remote Address:[::1]:44361
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:https: localhost:3000
Cache-Control:no-cache
Content-Type:application/json; charset=UTF-8
Date:Wed, 17 Aug 2016 13:07:29 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/10.0
Transfer-Encoding:chunked
X-AspNet-Version:4.0.30319
X-Content-Type-Options:nosniff
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcVXNlcnNccmFwaGFlbC5tb3JpblxTb3VyY2VcUmVwb3NcVGVhbXdvcmtTb2x1dGlvblxUZWFtd29yay5BcGlcc2lnbmFsclxuZWdvdGlhdGU=?=
but not my start request
Start Request
Request URL:https: localhost:44361/signalr/start?transport=webSockets&clientProtocol=1.5&connectionToken=tR9V6HAxpgmW7r5Ro%2BzJzhUoJdMUcmv7eDv1ZDM%2Fq6yur21LXCZ2Dg1rrNrDGc5VBXQzfanyisyZKOcWNP7SKOl3TsTkBl3luS4I2UnYtdw8biviZ5NtcE1caoXPi3lVHaHs%2FjQnicwGVDlmJdvRzA%3D%3D&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&_=1471439245327
Request Method:GET
Status Code:500 Internal Server Error
Remote Address:[::1]:44361
Response Headers
Cache-Control:private
Content-Type:text/html; charset=utf-8
Date:Wed, 17 Aug 2016 13:08:05 GMT
Server:Microsoft-IIS/10.0
Transfer-Encoding:chunked
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?QzpcVXNlcnNccmFwaGFlbC5tb3JpblxTb3VyY2VcUmVwb3NcVGVhbXdvcmtTb2x1dGlvblxUZWFtd29yay5BcGlcc2lnbmFsclxzdGFydA==?=
Here is my Startup class
[assembly: OwinStartup(typeof(Teamwork.Api.Startup))]
namespace Teamwork.Api
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration {
EnableJavaScriptProxies = false,
EnableDetailedErrors = true};
map.RunSignalR(hubConfiguration);
});
}
}
}
My hub
namespace Teamwork.Api.Hubs
{
public class ChatHub : Hub
{
public void TransferMessage(string receiver, string message)
{
var name = this.Context.User.Identity.Name;
var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
context.Clients.Group(name).AddMessage(name, message);
context.Clients.Group(receiver).AddMessage(receiver, message);
}
public override Task OnDisconnected(bool stopCalled)
{
var name = this.Context.User.Identity.Name;
Clients.All.changeStatus(name, 4);
return base.OnDisconnected(stopCalled);
}
public override Task OnConnected()
{
var name = this.Context.User.Identity.Name;
Clients.All.changeStatus(name, 0);
return Groups.Add(name, name);
}
}
}
I access it using an angularJS service provider that didn't have any problem with until i tried to subscribe to my hub
Service Provider
class ChatServiceProvider implements IChatServiceProvider {
baseUrl: string;
chatHub: HubProxy;
public setBaseUrl(url: string) {
this.baseUrl = url;
}
public $get(
$rootScope: fuse.interfaces.IRootScope
): IChatService {
var self = this;
var connection = $.hubConnection(self.baseUrl);
var chatHub = connection.createHubProxy("chatHub");
function initialize(): JQueryPromise<any> {
connection.logging = true;
return connection.start();
};
return {
chatHub: undefined,
initialize: () => {
return initialize()
},
on: function (eventName, callback) {
chatHub.on(eventName, function (result: any) {
$rootScope.$apply(function () {
if (callback) {
callback(result);
}
});
});
}
}
}
Controller
self.chatService.on("addMessage", function (name: string, message: string) {
this.addMessage(name, message);
})
this.$scope.reply = function (id: string, message: string) {
this.chatService.chatHub.invoke("transferMessage", id, message);
}
this.chatService.initialize()
.done(function (data: HubProxy) {
self.chatService.chatHub = data;
console.log("Connected");
})
.fail(function () { console.log("Failed") });
I tried to add this code to my Global.asax file without any success:
Context.Response.AppendHeader("Access-Control-Allow-Credentials", "true");
var referrer = Request.UrlReferrer;
if (Context.Request.Path.Contains("/signalr") && referrer != null){
Context.Response.AppendHeader("Access-Control-Allow-Origin", referrer.Scheme + ": " + referrer.Authority);
}
I've been looking for 4 days now for a similar issue and i can find none. As i am not proficient with webAPI and HtmlRequest, i may have miss something obvious. If not then any tips/ideas/answers would be greatly appreciated. If anything is missing, tell me and I'll add it as soon as possible.
Thanks to Holly which had a similar problem but I was too dumb to search correctly

ASP.NET Web API "400 Bad Request" on POST Request When Deploying to Test Server

I have a Single Page Application (SPA) with AngularJS as my front-end and .NET Web API as my backend. Everything works fine on my development machine, i.e. when I run it from Visual Studio (2015) under localhost. However, once published to our testing server, when sending POST requests to the Web API I get a "400 Bad Request" error. GET requests work fine. I am debugging it with Fiddler and when I look in the TextView tab it says "The underlying provider failed to Open". Here are some screenshots from Fiddler:
This is how the request and response look on my local machine:
This is the response headers on the the test server:
And the TextView on the test server:
The data being sent through the POST request is the same for both the localhost and the test server. Also, for both of them an authorization header is present. Other than the values for "Referer" and "Host", the only other difference I am noticing between them is that localhost is running on IIS/10.0 while the test server is on IIS/8.0.
The code for the AngularJS resource which calls the WebAPI is the following:
(function () {
"use strict";
angular
.module("mainApp")
.factory("incidentResource", ["$resource", "baseApiUrl", incidentResource]);
/// The factory function. The Angular $resource service and the appSettings
/// constant are injected as parameters.
function incidentResource($resource, baseApiUrl) {
return {
generateFile: $resource(baseApiUrl + "/api/Imports/PreviewOverlay", null,
{
'generate': { method: 'POST' }
})
};
}
})();
This is called from Angular code like so:
vm.generate = function () {
incidentResource.generateFile.generate(vm.divisionImports,
function (data) {
vm.successMessage.show = true;
},
function (response) {
vm.message = response.statusText + "\r\n";
if (response.data.exceptionMessage) {
vm.message += response.data.exceptionMessage;
}
});
}
And finally, my Web API controller looks like this:
[RoutePrefix("api/Imports")]
public class ImportController : BaseController
{
[Authorize]
[HttpPost]
[Route("PreviewOverlay")]
public IHttpActionResult GenerateFile(DivisionImport[] chargedIncidents)
{
try
{
// Get the name of the user currently logged in
string UserName = this.GetCurrentUserIdFromRequest();
List<DivisionImport> incidentsList = new List<DivisionImport>();
incidentsList.AddRange(chargedIncidents);
this.incidentFileBuilder.GenerateFile(FileType.Delimited, incidentsList);
return this.Ok();
}
catch (Exception ex)
{
return this.BadRequest(ex.Message);
}
}
}
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class BaseController : ApiController
{
}
What could be causing this error?
As #Dan Jul pointed out, the error was caused by a faulty database connection string. While deploying my code to our test server, we changed the connection configuration file to a different one (for the test server) and it contained a connection string with a syntax error.
Things are working now.

Categories