I have a Blazor WebAssembly app which is server hosted.
When I deploy it on an internal work network, the address is just the IP address, e.g. http://192.168.1.23. That works, but it's not so user friendly. I want it to be http://192.168.1.23/myapp.
I've done some reading on this here (Microsoft), and also here (Stackoverflow). They suggest a couple of things:
In Client side code, index.html, change <base href="/" /> to <base href="/myapp/" />.
In Server side code, Startup.cs, add app.UsePathBase("player"); early on in the Configure() method.
Microsoft also says how to edit the launch settings so that debug still works normally, and they include adding the following to the launchSettings.json file:
"commandLineArgs": "--pathbase=/myapp",
"launchUrl": "myapp"
They don't say if this is in the Client or Server launchSettings.json file, and I can't get it to work anyway. Even if I add "launchUrl": "https://www.google.com" everywhere, nothing different happens when I run it.
Ignoring number 3 above though, the app will start, and I can get to the correct place by manually adding /myapp to the address. So far so good.
I am using cookie authentication though, and when I try to retrieve the user details from the user details from the HttpContext using this method on a hub:
public static User GetAuthenticatedUser(this HttpContext context)
{
var idClaim = context.User.Claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.NameIdentifier));
var nameClaim = context.User.Claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Name));
return new User
{
Id = int.Parse(idClaim.Value),
Name = nameClaim.Value
};
}
It fails, with each claim being null. It did not before I set the base path. How can I overcome this issue?
Note: It works on a regular controller, it's specifically a hub it is failing on, so it's as if the hub is not receiving the same HttpContext as before. The hub was also setup in Startup.cs, with the following in the Configure() method:
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<MyHub>("/myhub1");
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
Any advice is much appreciated.
I have an application where i have 2 instances of it running on the same IIS server.
/Site1
/Site2
same source code in both, just different settings. I have signalR code on both sites, but i would like Site2 to use the signalR server from Site1.
I have this working so that if changes are made on Site1, Site2 knows to refresh, and that works fine. THE PROBLEM is that if server changes (not javascript) are made on Site2, Site1 doesn't get them. Below is my code:
Startup.cs
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
#if DEBUG
EnableDetailedErrors = true
#endif
};
map.RunSignalR(hubConfiguration);
});
javascript code:
$.connection.hub.url = "http://servername/Site1/signalr";
...$.connection.start etc
All of that seems to work fine, but what i can't find anywhere is how to push settings in the C# code from Site2 to Site1.
random c# code:
var hub = GlobalHost.ConnectionManager.GetHubContext<myHub>();
this globalhost.connectionmanager.gethubcontext is always pointing to itself. How can i get Site2 to point to Site1 in the last section? I've tried looking into editing Startup.cs to use MapSignalR(..path,...), but the path doesn't take absolute URLs, it has to start with '/', so it won't go up a level.
Any ideas or am i missing something basic?
Apparently what i'm looking for is a backplane. https://learn.microsoft.com/en-us/aspnet/signalr/overview/performance/scaleout-in-signalr . super easy to set up, and fixed my problem immediately (without any of the javascript changes above needed).
So I am very new to SignalR, in fact I've only been using it for a couple of days now. Anyway, I am getting the error below when my application first starts up:
The code for the application in question is located in two projects, a Web API and a Single Page Application (SPA). The first one has my backend code (C#) and the second one my client-side code (AngularJS). I think the problem might be due to the fact that the projects in question run on different ports. The Web API, where my SignalR hub lives, is on port 60161 and the SPA is on 60813. My hub is declared like so:
public class ReportHub : Hub
{
public void SendReportProgress(IList<ReportProgress> reportProgress)
{
this.Clients.All.broadcastReportProgress(reportProgress);
}
public override Task OnConnected()
{
this.Clients.All.newConnection();
return base.OnConnected();
}
}
and then in my Startup.cs file for my Web API I initialize SignalR like this:
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.Services.Replace(typeof(IHttpControllerActivator), new NinjectFactory());
config.MessageHandlers.Add(new MessageHandler());
//set up OAuth and Cors
this.ConfigureOAuth(app);
config.EnableCors();
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
// Setting up SignalR
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
map.RunSignalR(new HubConfiguration { EnableJSONP = true });
});
//set up json formatters
FormatterConfig.RegisterFormatters(config.Formatters);
WebApiConfig.Register(config);
app.UseWebApi(config);
}
For my client-side code I use an Angular SignalR API called angular-signalr-hub (Angular-signalr-hub). The client-side follows:
angular
.module("mainApp")
.factory("reportHubService", ["$rootScope", "Hub", reportHubService]);
/// The factory function
function reportHubService($rootScope, Hub) {
var vm = this;
vm.reportName = "None";
// Setting up the SignalR hub
var hub = new Hub("reportHub", {
listeners: {
'newConnection': function(id) {
vm.reportName = "SignalR connected!";
$rootScope.$apply();
},
'broadcastReportProgress': function (reportProgress) {
vm.reportName = reportProgress.reportName;
$rootScope.$apply();
}
},
errorHandler: function(error) {
},
hubDisconnected: function () {
if (hub.connection.lastError) {
hub.connection.start();
}
},
transport: 'webSockets',
logging: true
//rootPath: 'http://localhost:60161/signalr'
});
I did some googling yesterday and one of the suggestions I came upon was to set the SignalR URL to the one of my Web API, which I did (the commented out line above). When I uncomment the line in question, that does seem to do something because if I now go to http://localhost:60161/signalr/hubs in my browser, it does show me the dynamically generated proxy file:
and when I run my application I no longer get the error above, but now it doesn't seem to connect. It gets to the negotiate line and it stops there:
I think it should look like this (this is from a SignalR tutorial I found):
In addition, none of my listeners (declared in my Angular code above) get called, so something is still now working quite right. There should be more lines in the log to the effect that connection was successfully established, etc. What could be the problem here?
UPDATE: upon further debugging i found out the problem is most likely being caused by the ProtocolVersion property being different between the client and the result here:
Because of that it seems it just exists and fails to establish connection.
I figured out what the problem was. My SignalR dependencies were out of date and because of that my client and server versions differed. All I had to do was update (via NuGet Package Manager) all SignalR dependencies to the latest version and now it works.
As a side note, SignalR was not very good at telling me what was wrong. In fact, no error message was displayed, unless of course there was some additional logging somewhere that had to be found or turned on, in addition to the logging I already had (turned on). Either way, it's either not logging certain errors or it makes it difficult to figure out how to turn on all logging. I had to go and debug the JQuery SignalR api to figure out what the problem was, which was a time consuming endeavour.
I'm trying to use oauth with Google in ASP.NET MVC 5.
In Google's developer console I put for the redirect uri:
www.mydomain.com/account/externallogincallback
and thought that this will do. But it didn't.
I put:
www.mydomain.com/signin-google
and it worked!
I tried to search the string "signin-google" in my project but couldn't find it anywhere.
Can someone tell me what is going on? why is that so? thanks.
I am too lazy to write a properly formatted answer, I placed these comments in code for myself to remember how to resolve this issue. It is not really an issue, just something I never bothered to read properly :) But this is what you can do to make it work. There 2 options how you can do it. I have tried both and both options work just fine. I went with the first one for now, it really doesnt matter. Here are my comments in Startup.Auth.cs file.
// My notes to resolve Google Error: redirect_uri_mismatch error
// By default GoogleOAuth2AuthenticationOptions has CallbackPath defined as "/signin-google"
// https://msdn.microsoft.com/en-us/library/microsoft.owin.security.google.googleoauth2authenticationoptions(v=vs.113).aspx
// But the real path should be Controller/Action: for this application it is "/Account/ExternalLoginCallback"
// There are 2 ways to define it properly:
// 1) Add a new route in RouteConfig.cs that will map "/signin-google" into "/Account/ExternalLoginCallback":
// routes.MapRoute(name: "signin-google", url: "signin-google", defaults: new { controller = "Account", action = "ExternalLoginCallback" });
// Remember, in Google Developers Console you must have your "/signin-google" redirect URI, since that is what your app sends to Google
// 2) Completely overwrite built-in "/signin-google" path.
// Owerwrite CallbackPath right here by adding this line after ClientSecret:
// CallbackPath = new PathString("/Account/ExternalLoginCallback")
// Remember, in Google Developers Console you must have "/Account/ExternalLoginCallback" redirect URI, since now that is what your app sends to Google
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "xxxxxxxxxxxxxxxxxxxx",
ClientSecret = "xxxxxxxxxxxxxxxxxxxxxxxx"
});
I am having a problem where I try to open my ASP.NET MVC application but I get the ASP.NET error page which says this:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /EventScheduler/account.aspx/login
Version Information: Microsoft .NET Framework Version:2.0.50727.3053; ASP.NET Version:2.0.50727.3053**
I am using the URL trick from this blog post and that is why I have the .aspx in the URL:
http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/
It works on my other sandbox server (not a dev machine), and now I just deployed it to my production site as a new virtual directory, but for some reason it seems like it's actually looking for a .aspx file.
Any ideas? I think I must be forgetting a step.
I got the same error when building. The default is to use URLRoute settings for navigating. If you select the "Set as Startup Page" property by right clicking any cshtml page, that throws this error because there are always a routing to the current page under the Global.asax file.
Look at Project Properties for Startup Path and delete it.
I found the solution for this problem, you don't have to delete the global.asax, as it contains some valuable info for your proyect to run smoothly, instead have a look at your controller's name, in my case, my controller was named something as MyController.cs and in the global.asax it's trying to reference a Home Controller.
Look for this lines in the global asax
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
in my case i had to get like this to work
new { controller = "My", action = "Index", id = UrlParameter.Optional }
Make sure you're not telling IIS to check and see if a file exists before serving it up. This one has bitten me a couple times. Do the following:
Open IIS manager. Right click on your MVC website and click properties. Open the Virtual Directory tab. Click the Configuration... button. Under Wildcard application maps, make sure you have a mapping to c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll. MAKE SURE "Verify the file exists" IS NOT CHECKED!
You should carefully review your Route Values.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
In this case, ensure you have your Controller 'Home' as the application will fail to load if there is no HomeController with Index Action. In My case I had HomesController and I missed the 's' infront of the Home. I Fixed the Name mismatch and this resolved the issue on both my local environment and on my server.
If you're running IIS 6 and above, make sure the application pool your MVC app. is using is set to Integrated Managed Pipeline Mode. I had mine set to Classic by mistake and the same error occurred.
The page is not found cause the associated controller doesn't exit. Just create the specific Controller. If you try to show the home page, and use Visual Studio 2015, follow this steps:
Right click on Controller folder, and then select Add > Controller;
Select MVC 5 Controller - Empty;
Click in Add;
Put HomeController for the controller name;
Build the project and after Run your project again
I hope this help
Two Things Needs To Be Ensure:
1) Route should be proper in Global.ascx file
2) Don't forget to add reference of Controller Project in your Web Project (view is in separate project from controller)
The second one is my case.
Had the same issue, in my case the cause was that the web.config file was missing in the virtual dir folder.
I got the same error while building a MVC application.
In my case it happened because I forgot to add the string "Controller" in my controller name.
Error With
public class ProductType : BaseController
{
public ProductType()
{
}
}
Resolved
public class ProductTypeController : BaseController
{
public ProductTypeController ()
{
}
}
In your Project open Global.asax.cs then right click on Method RouteConfig.RegisterRoutes(RouteTable.Routes); then click Go To Definition
then at defaults: new { controller = "Home", action = "Index", id =UrlParameter.Optional}
then change then Names of "Home" to your own controller Name and Index to your own View Name if you have changed the Names other then "HomeController" and "Index"
Hope your Problem will be Solved.
Step 1 : Check to see if you have received the following update? http://support.microsoft.com/kb/894670 If you have you might want to follow this procedure and see if it works for you. It worked partially for me.
The item where it mentions the additional "/" to be removed is not entirely true but it did give me some insight to change my project properties just a bit.
step 2 : Right click on your properties for your Web Project in your Solun.
Select WEB > Choose Current Page instead of Specific Page.
step 3 : Go into your project where you keep your *.aspx's select a start page. (Should be the same as the current page or choose another one of your choice :) )
Hit Debug Run.
Suppose source code copy from other places.
Sometime, if you use Virtual Directory in your application url like:
http://localhost:50385/myapp/#/
No route will pick up the request.
solution:
Explicitly click the button 'create a virtual directory' in your project file.
Go to any page you want to see it in browser right click--> view in browser.
this way working with me.
Upon hours of debugging, it was just an c# error in my html view.
Check your view and track down any error
Don't comment c# code using html style ie
Open your Controller.cs file and near your public ActionResult Index(), in place of Index write the name of your page you want to run in the browser. For me it was public ActionResult Login().
Remember to use PUBLIC for ActionResult:
public ActionResult Details(int id)
{
return View();
}
instead of
ActionResult Details(int id)
{
return View();
}
you must check if you implemented the page in the controller
for example:
public ActionResult Register()
{
return View();
}
I had a similar problem. But I was working with Episerver locally with ssl enabled. When I wasn't getting a
Server Error in '/' Application.
I was getting a Insecure connection error.
In the end, for me, this post on PluralSight together with configuring the website urls, accordingly with the ssl link set up on the project's config, on Admin's Manage Website's screen solved the problem.
In my case, I needed to replace this:
#Html.ActionLink("Return license", "Licenses_Revoke", "Licenses", new { id = userLicense.Id }, null)
With this:
Return license
<script type="text/javascript">
function returnLicense(e) {
e.preventDefault();
$.post('#Url.Action("Licenses_Revoke", "Licenses", new { id = Model.Customer.AspNetUser.UserLicenses.First().Id })', getAntiForgery())
.done(function (res) {
window.location.reload();
});
}
</script>
Even if I don't understand why. Suggestions are welcome!
For me its solved follow the following steps :
One reason for this occur is if you don't have a start page or wrong start page set under your web project's properties. So do this:
1- Right click on your MVC project
2- Choose "Properties"
3- Select the "Web" tab
4- Select "Specific Page"
Assuming you have a controller called HomeController and an action method called Index, enter "home/index" in to the text box corresponding to the "Specific Page" radio button.
Now, if you launch your web application, it will take you to the view rendered by the HomeController's Index action method.
It needs you to add a Web Form, just go to add on properties -> new item -> Web Form. Then wen you run it, it will work. Simple
I had the same problem caused by my script below. The problem was caused by url variable. When I added http://|web server name|/|application name| in front of /Reports/ReportPage.aspx ... it started to work.
<script>
$(document).ready(function () {
DisplayReport();
});
function DisplayReport() {
var url = '/Reports/ReportPage.aspx?ReportName=AssignmentReport';
if (url === '')
return;
var myFrame = document.getElementById('frmReportViewer');
if (myFrame !== null) {
if (myFrame.contentWindow !== null && myFrame.contentWindow.location !== null) {
myFrame.contentWindow.location = url;
}
else {
myFrame.setAttribute('src', url);
}
}
}
</script>