I have an Asp.Net web Api 2, using .net 4.7.2 version. And Sentry documents saying for .Net 4.7.2 version I can use Sentry nuget rather than ravenClient nuget. But when I installed Sentry nuget and used Sentry SDK, nothing working, no events are being sent to Sentry.
Below is my WebApi config file where I tried this Sentry.
public static void Register(HttpConfiguration config)
{
using (SentrySdk.Init(o =>
{
o.Dsn = myDsn;
// When configuring for the first time, to see what the SDK is doing:
o.Debug = true;
// Set traces_sample_rate to 1.0 to capture 100% of transactions for performance monitoring.
// We recommend adjusting this value in production.
o.TracesSampleRate = 1.0;
}))
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
//routeTemplate: "api/{controller}/{id}",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional }
);
string date = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
SentrySdk.CaptureMessage("Something went wrong " + date);
}
}
Can anyone help me here?
Thanks
You have the Sentry initialization code within using block which is a common pattern for something like a CLI (so it flushes events before exiting).
With a long running process that's managed outside of your control like ASP.NET (not Core) you can call Init and then call Dispose or Close on the hook that's triggered before the process exits.
For example:
https://github.com/getsentry/examples/blob/81fb90b957ce9a8c1f6222d1603d0fa499ecba7e/dotnet/AspNetMvc5Ef6/Global.asax.cs#L21-L51
Related
I am using ASP.NET FW 4.6.1; Microsft.AspNet.WebApi 5.2.7; EF 6.4.
I have the issue below when starting my project.
Method request.Files is not supported (please see image)
public static class WebApiConfig
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "<Pending>")]
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//Enable cross domain request
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.Filters.Add(new ErrorHandlers.AiHandleErrorAttribute());
**config.Filters.Add(new UploadFileFilterAttribute());**
config.MessageHandlers.Add(new RequestTabletMessageHandler());
config.MessageHandlers.Add(new RequestLoggingMessageHandler());
config.Services.Add(typeof(IExceptionLogger), new CustomExceptionLogger());
}
}
The reason it is not supported is because the file buffer stream has already been parsed (or parsing has started) at a previous point in the request pipeline. You should look at other filters/modules in your pipeline and see if any of them touch the files in the incoming request. You might find that simply commenting out other filters (such as ErrorHandlers.AiHandleErrorAttribute() for example) and rerunning could be used to quickly determine which filter/module is doing the parsing. Once you have figured that out, you need to decide how you are going to handle multiple parses of the files. One option is to only use one module, another would be to buffer it into a memory stream/block of memory and have both/all modules access that copy instead. Hope this helps.
My project is Owin self-hosted, it provides Web API endpoints and web socket endpoints.
Here is the relevant config code in the project's startup class
Owin WebSocket is used here
using Owin;
using Owin.WebSocket.Extensions;
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "api",
routeTemplate: "api/{version}/{controller}"
);
config.EnsureInitialized();
app.MapWebSocketRoute<WebSocket>("/api/v1/socket/test");
app.UseWebApi(config);
}
Works smoothly, when the app is launched I can consume the web api via "http://{host}/api/v1/test" and use the websockets by: "ws://{host}/api/v1/socket/test"
Then I decided to add some integration tests. I use Owin Test Server here. In TestServer.Create the config is identical:
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "api",
routeTemplate: "api/{version}/{controller}"
);
config.EnsureInitialized();
app.MapWebSocketRoute<WebSocket>("/api/v1/socket/test");
app.UseWebApi(config);
Test method for api
var url = new UriBuilder()
{
Scheme = "http",
Path = "/api/v1/test"
}.Uri;;
var result = client.GetAsync(url).Result;
Works nicely. But does not work for web socket:
var wsUri = new UriBuilder()
{
Scheme = "ws",
Path = "/api/v1/socket/test"
}.Uri;
//create websocket client, connect it and to server
var wsc = new ClientWebSocket();
Task.Run(async () =>
{
await wsc.ConnectAsync(wsUri, CancellationToken.None);
var a = wsc.State; // Here error thrown: No connection could be made because the target machine actively refused it 127.0.0.1:80
}).GetAwaiter().GetResult();
Why No connection could be made here? It seems like the testing server can only support regular http request not websocket. But this is not the case in the main app where the identical setting and framework is used. What am I missing here? I have been fiddling with this for hours to no avail...
Found the answer. The TestServer.Create<Startup>() only starts just the in-memory instance where the url is not available. The web socket client however relies on the url to work. So the solution is to user the overload WebApp.Start<Startup>(Settings.WebApiUrl) (it starts a web app on the url you provide)
WebApp.Start(new StartOptions("http://localhost:8989"), startup =>
{
startup.MapWebSocketRoute<TestConnection>();
startup.MapWebSocketRoute<TestConnection>("/ws", sResolver);
startup.MapWebSocketPattern<TestConnection>("/captures/(?<capture1>.+)/(?<capture2>.+)", sResolver);
});
Ref
Created an MVC application using framework 6 & ASP.NET vNext.
Application looks for a database table using the Entity Framework. The connection string which is present in config.json file is not readable from application reporting back the exception below.
EXCEPTION
"No data stores are configured. Configure a data store using On Configuring or by creating an ImmutableDbContextOptions with a data store configured and passing it to the context."
config.json
{
"Data": {
"DefaultConnection": {
"Context": "Server= .;Database=Database1;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
}
startup.cs
public void Configure(IBuilder app)
{
// Setup configuration sources
var configuration = new Configuration();
configuration.AddJsonFile("config.json");
configuration.AddEnvironmentVariables();
// Set up application services
app.UseServices(services =>
{
// Add EF services to the services container
services.AddEntityFramework()
.AddSqlServer();
// Configure DbContext
services.SetupOptions<DbContextOptions>(options =>
{
options.UseSqlServer(configuration.Get("Data:DefaultConnection:Context") );
});
// Add Identity services to the services container
services.AddIdentity<ApplicationUser>()
.AddEntityFramework<ApplicationUser, ApplicationDbContext>()
.AddHttpSignIn();
// Add MVC services to the services container
services.AddMvc();
});
// Enable Browser Link support
app.UseBrowserLink();
// Add static files to the request pipeline
app.UseStaticFiles();
// Add cookie-based authentication to the request pipeline
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Home/Details"),
});
This maybe related to the Identity Context.
Thank you for any advice.
sql server 2008
MVC6
asp.net vNext
Configured a data store by creating an DbContext with a data store configured and passing it to the context.
public TestContext(IServiceProvider serviceProvider, IOptionsAccessor<TestDbContextOptions> optionsAccessor)
: base(serviceProvider, optionsAccessor.Options)
{
if (!_created)
{
Database.EnsureCreated();
_created = true;
}
}
Resolved my issue thanks.
I am using SignalR 2.0. Everything works fine when running locally on my VS 2012. But when I publish the site on IIS, it breaks. The site loads but one of the scripts returns 404 Not Found. The script is something like.
https://example.com/signalr/negotiate?xxx
This path doesn't exist indeed. The correct path should be:
https://example.com/private/signalr/negotiate?xxx
Note the part in bold.
Inside the WebSite (https://example.com/) I have another Application (https://example.com/private/). This one is using SignalR.
This seems like a bug in SignalR since the signalr/hubs path is accessible from my private site.
I had a similar problem.
Here is the documentation for configuring the /signalr URL.
However, my solution differed from the docs.
Instead of changing the standard app.MapSignalR(), I changed my client code to use /MyApp/signalr. Here is the code where "MyApp" is the virtual directory of my web application.
var connection = $.hubConnection('/MyApp/signalr', {useDefaultPath: false});
var changesHub = connection.createHubProxy('changesHub');
changesHub.on('userCountChanged', function (count) {
$('#user-count').text(count);
});
connection.start().done(function () {
console.log('Hub has started');
changesHub.invoke('subscribeToChanges', user.id);
});
I tried the other way around (change the MapSignalR to the /signalr path) but this did not work and the negotiation was still routed to /MyApp/signalr/negotiate.
I had the same problem, with an application running in the IIS Default Web Site.
All the Microsoft examples show the hub url with a starting \, and I had copied those examples. But this meant that the signalr routing was from the Default Web Site rather than the application. Removing the leading \ solved it.
So I used endpoints in Startup.cs like:
endpoints.MapHub<MyHub>("myHub");
and hub connections in Javascript like:
var connection = new signalR.HubConnectionBuilder().withUrl("myHub").build();
I had the same issue when web site with signalr is not running as root site. Below solution worked for me. instead of using /signalr, use ../signalr. it will work with any site name folder. no hardcoded name 'MyApp'
var connection = $.hubConnection('../signalr', {useDefaultPath: false});
Had the same issue. web sites running as virtual directories of the root site. For some reason prefixing with ../ as in ../signalr didn't work, but ./signalr did.
My sample code:
function initSR() {
// logs signalr messages
$.connection.hub.logging = true;
// Declare a proxy to reference the hub.
var chat = $.connection.myHub;
$.connection.hub.url = "./signalr";
$.connection.hub.start();
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (message) {
// Process Message, take action upon receipt
alert(message);
};
}
I had the same problem, it is all about CORS, you should add Host URL in CORS config in Startup.cs like this:
services.AddCors(option =>
{
option.AddPolicy("AutomationCors", builder =>
{
builder.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("YOUR LOCALHOST URL",
"YOUR HOST URL")
.AllowCredentials();
});
});
I faced the same problem. The mistake i was doing that i was calling the wrong endpoint url like i was mapping the Signal Url in Configure service like /notification but calling [API-Host]/api/notification. Removing the api from url and calling [API-Host]/notification fixed for me.
Probably you added MapSignalR() in your Application (https://example.com/private/).
If you want it on the root, then do the configuration on your WebSite (https://example.com/)
#styfle point me in the right direction the problem can be resolve in a more flexible way injecting BASE_URL (at least in angular 4)
import { Injectable, Inject } from '#angular/core';
import { HubConnection } from '#microsoft/signalr';
import * as signalR from '#microsoft/signalr';
import { Subject, Observable } from 'rxjs';
#Injectable()
export class SignalRService {
private hubConnection: HubConnection;
private message: Subject<any>;
constructor(#Inject('BASE_URL') private baseUrl: string) {
}
public connect() {
this.message = new Subject<any>();
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl(this.baseUrl+"notification-hub")
.withAutomaticReconnect()
.build();
// ...
}
}
I have a controller called "UploadsController". I have a GET action like so:
public string GetUpload([FromUri]string action)
{
return "hey " + action;
}
If I navigate to the following API URL in my browser, I get a successful response.
http://localhost:52841/MySite/api/uploads?action=testaction
However, when I try calling the API from code-behind in my WebForms app, I get a 404 response.
Here's what I have in my Global.aspx file (even though I believe the first should do it):
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
RouteTable.Routes.MapHttpRoute(
name: "Default2Api",
routeTemplate: "api/{controller}/{action}",
defaults: new { controller = "Uploads", action = "GetUpload" });
Here's how I'm calling the API:
// Send a request asynchronously continue when complete
client.GetAsync("http://localhost:52841/MySite/api/uploads?action=testaction").ContinueWith(
(requestTask) =>
{
// Get HTTP response from completed task.
HttpResponseMessage response = requestTask.Result;
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously as JsonValue
response.Content.ReadAsAsync<string>().ContinueWith(
(readTask) =>
{
var result = readTask.Result;
//Do something with the result
});
});
I thought I've done this before (with the RC version, using RTM now), but I can't seem to get this one.
As a side note, the request isn't showing in fiddler for some reason, which is kind of annoying when you're trying to debug these kind of stuff.
Any help is appreciated.
Try naming your query string parameter to something else (Right now it is "action"). I think that's one reason it's causing problems. Since MVC is convention-based, that might be causing problems.
Also in your route declaration, try adding the query string parameter (Let me call it custAction).
And declare custom route before default route.
Code sample:
RouteTable.Routes.MapHttpRoute(
name: "Default2Api",
routeTemplate: "api/{controller}/{action}",
defaults: new { controller = "Uploads", action = "GetUpload", custAction = RouteParameter.Optional});
Yes I have been through the same problem most likely your issue is that webapi doesnt allow cross domain calls by default or at least this is what I know about it.
You need to add a CORS support to your web api code, follow the link this guy has shown how to add CORS to your webapi
http://code.msdn.microsoft.com/CORS-support-in-ASPNET-Web-01e9980a
Good Luck.