Calling an MVC3 action from a SQL CLR stored procedure - asp.net-mvc-3

I'm working on a CLR stored procedure that calls a controller action in an ASP.NET MVC3 application that uses Windows Authentication (everything else is disabled). The Web server is IIS 7.5 running on Windows Server 2008 R2 Standard. The database server is SQL Server 2008 R2 Enterprise Edition. Here is the code of the CLR proc:
[SqlProcedure]
public static void UpdateModels()
{
Uri uri = null;
HttpWebRequest rq;
HttpWebResponse rsp;
Uri.TryCreate("http://testserver/RPM/Configuration/UpdateModels", UriKind.Absolute, out uri);
rq = (HttpWebRequest)HttpWebRequest.Create(uri);
rq.Method = WebRequestMethods.Http.Get;
rsp = (HttpWebResponse)rq.GetResponse();
}
I was able to deploy the assembly to SQL Server without problem, but when I run it, I get the following error:
Msg 6522, Level 16, State 1, Procedure UpdateModels, Line 0
A .NET Framework error occurred during execution of user-defined routine or aggregate "UpdateModels":
System.Net.WebException: The remote server returned an error: (401) Unauthorized.
System.Net.WebException:
at System.Net.HttpWebRequest.GetResponse()
at StoredProcedures.UpdateModels()
.
This occurs when I call the SP from a SQL Agent job (run under my credentials), when I EXEC it from a SSMS query window (again, my credentials), or any other method I've thought to try. I am an authorized user of the Web application and able to call that controller method just fine from the application itself.
If I change the URL to be just "http://testserver", it runs fine (of course, it doesn't do anything), but if I add "RPM" to the URL, it fails, so it seems the problem is with the application itself, not with the server or its default site. Also, if I enable anonymous auth, it works, so somehow the Windows credentials are not being passed to the site. Checking the log confirms this:
2012-02-23 12:51:33 10.1.1.1 GET /RPM/Configuration/UpdateModels - 80 - 10.2.2.2- 302 0 0 218
The credentials are not being passed. I've tried using impersonation within the CLR SP code, but that has not helped. As I'm sure is obvious, I'm pretty new at this stuff and am probably doing something daft. If someone could set me on the right course, I'd be grateful!
TIA,
Jeff

Well, as I feared, I was doing something daft. Turns out impersonation was the answer, but I simply needed to set the impersonation level:
rq.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
before calling the GetResponse method. After doing that, the credentials supplied were passed to the MVC3 controller just as I'd originally expected.
Thought I'd post this just in case anyone else struggles with it the way I did.
Jeff

Related

.NET Core 5 GET Action Called Twice

Environment
.NET Core 5 Web Application
IIS 10
Azure VM
Issue
Executing a GET action results in that action being called a second time. The first call shows cookie information. The second does not show cookie information.
What we've tried:
Occurs for GET requests but not POST requests
Occurs without a view (NOT a javascript issue)
Browser does not show two requests. This occurs server-side.
Does not occur in Firefox Privacy Mode
Does not occur on localhost. Only in production.
Occurs with HTTPS off
Fork of the solution does not exhibit this behavior (makes middleware unlikely cause)
Best guesses:
.NET 5 (deprecated) or dependencies (a bad developer blames his tools)
IIS Settings
Session
Code example:
Controller
// no other filters
[HttpGet]
public IActionResult DupeRequestTest()
{
// database insert with Dapper
var sql = #"INSERT INTO TrackingTable
(CookieJson, CreateDate)
VALUES(#CookieJson, GETDATE());";
using var con = new SqlConnection(_connectionString);
con.Open();
con.Execute(sql, new
{
CookieJson=JsonConvert.SerializeObject(Request.Cookies),
});
// returning a status code so no View, javascript, or other requests
return StatusCode(200);
}
Database results:
CookieJson
CreateDate
[{"Key":"SessionId","Value":"ac6f292c-1ca1-5179-9123-78a04d382dea"}]
2022-10-25 09:46:30.523
[]
2022-10-25 09:46:30.770
Thank you. Any help, such as next testing steps, would be appreciated - short of building a new app.
I'm sure the answer is either very stupid or very hidden.

Blazor app not running server code when on hosted server

I have a blazor web assembly app and I have 3 projects that were created. The client, server and shared. I assume all of these are deployed as standard when using the webdeploy?
The site works in that it displays the pages etc. However when I go to a page that contacts the server project via the Http.PostAsJsonAsync() method, I get the blazor error page (which I setup to say "oops").
Obviously I get no details as to what is going wrong. So I have no idea what is happening. Is the server app compiled into the Web assembly app? If so why would it not be running the server code? Plus I suppose the other question is how do I get it to report the error so that I can get an idea as to what is going wrong?
It works absolutely fine when running it through Visual Studio.
This is the first time I have deployed to a hosted server so there is a very high chance I have done something wrong...
The method I am calling literally does nothing other than returning a 200 message. So I assume the issue is with calling the server method itself.
Firstly, use Logging:
https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/logging?view=aspnetcore-5.0&pivots=server
#inject ILogger<MyComponent> Logger
Then wrap your Http.PostAsJsonAsync() call in a Try Catch block.
Log the error in the Catch block:
try
{
await Http.PostAsJsonAsync()
}
catch (Exception e)
{
Logger.LogError(e);
}
After deployment, edit your web.config file:
<aspNetCore processPath="dotnet"
arguments=".\Hospitillity.App.Server.dll"
stdoutLogEnabled="true" // <<< MAKE THIS true
stdoutLogFile=".\logs\stdout"
hostingModel="inprocess">
Note, the setting stdoutLogEnabled="true". This will cause your hosting provider to generate log files.
Then recycle your app pool on your hosting provider.
Connect to your website again, and after the error you should have some more details about error logged in
\logs\stdout_nnnnnnnnnnnnnn_nnnnnn.log
on the hosting server.
Take it from there ...

ASP.NET Core constant requests to home controller

I have an ASP.NET Core MVC application hosted on Google Compute Engine, and when I check the logs, it seems that www.mysite.com/home/index is constantly being requested even though I am not searching that URL in my browser and nobody else knows the actual URL. Why is this? I am concerned that it may be interfering with some of my processes.
I am running the app on Windows Server 2016 and I often Remote Desktop into it. Could either of these be the reason behind the logs I am getting?
{"#t":"2019-01-01T09:37:24.4301536Z","#m":"Request starting HTTP/1.1 GET http://10.142.0.4/ ","#i":"ca22a1cb","Protocol":"HTTP/1.1","Method":"GET","ContentType":null,"ContentLength":null,"Scheme":"http","Host":"10.142.0.4","PathBase":"","Path":"/","QueryString":"","HostingRequestStartingLog":"Request starting HTTP/1.1 GET http://10.142.0.4/ ","EventId":{"Id":1},"SourceContext":"Microsoft.AspNetCore.Hosting.Internal.WebHost","RequestId":"0HLJFPIU5NJ9V:00000001","RequestPath":"/","CorrelationId":null,"ConnectionId":"0HLJFPIU5NJ9V"}
{"#t":"2019-01-01T09:37:24.5299320Z","#m":"Route matched with \"{action = \\\"Index\\\", controller = \\\"Home\\\"}\". Executing action \"TelebotApplication.Controllers.HomeController.Index (TelebotApplication)\"","#i":"a44c0341","RouteData":"{action = \"Index\", controller = \"Home\"}","ActionName":"TelebotApplication.Controllers.HomeController.Index (TelebotApplication)","EventId":{"Id":1},"SourceContext":"Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker","ActionId":"dc996f72-2933-4b90-9a5e-ccbfe11d91ba","RequestId":"0HLJFPIU5NJ9V:00000001","RequestPath":"/","CorrelationId":null,"ConnectionId":"0HLJFPIU5NJ9V"}
{"#t":"2019-01-01T09:37:24.5405482Z","#m":"Executing action method \"TelebotApplication.Controllers.HomeController.Index (TelebotApplication)\" - Validation state: Valid","#i":"dad538d7","ActionName":"TelebotApplication.Controllers.HomeController.Index (TelebotApplication)","ValidationState":"Valid","EventId":{"Id":1},"SourceContext":"Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker","ActionId":"dc996f72-2933-4b90-9a5e-ccbfe11d91ba","RequestId":"0HLJFPIU5NJ9V:00000001","RequestPath":"/","CorrelationId":null,"ConnectionId":"0HLJFPIU5NJ9V"}
{"#t":"2019-01-01T09:37:24.5441766Z","#m":"Executed action method \"TelebotApplication.Controllers.HomeController.Index (TelebotApplication)\", returned result \"Microsoft.AspNetCore.Mvc.ViewResult\" in 0.4835ms.","#i":"50a9e262","ActionName":"TelebotApplication.Controllers.HomeController.Index (TelebotApplication)","ActionResult":"Microsoft.AspNetCore.Mvc.ViewResult","ElapsedMilliseconds":0.48350000000000004,"EventId":{"Id":2},"SourceContext":"Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker","ActionId":"dc996f72-2933-4b90-9a5e-ccbfe11d91ba","RequestId":"0HLJFPIU5NJ9V:00000001","RequestPath":"/","CorrelationId":null,"ConnectionId":"0HLJFPIU5NJ9V"}
This seems to pretty much repeat itself endlessly.
Thanks
when I check the logs, it seems that www.mysite.com/home/index is constantly being requested even though I am not searching that URL in my browser and nobody else knows the actual URL
For this issue, it is caused by Health checking you configured in the GCP.
The issue I am facing, is occassionally, public static void
Main(string[] args) is re-entered without my instruction.
For this issue, it is usually caused by the application recycling. Exceptions in request would not make application recycling.

Classic ASP error '800a01b6' Object doesn't support this property or method

I have an error that I cannot resolve, the server is showing this
Microsoft VBScript runtime error '800a01b6'
Object doesn't support this property or method: 'SharedSession'
/includes/minicart.asp, line 183
In minicart.asp we have the following code:
(180)dim SharedSession
(181)set SharedSession = Server.CreateObject("SessionMgr.Session2")
(183)dim miniCartXML: miniCartXML = "" & SharedSession("minicart")
For some reason when the client clears their browsing history the error goes away but it will eventually come back again.... ??
The server is Windows 2008 r2 64bit. The app is running in IIS7 with 32bit enabled.

Sharepoint 2010 Client Object Model Remote Access via HTTPS

I was encouraged to learn that the Sharepoint 2010 Client Object Model essentially wraps remote calls to the server. So, I copied the Microsoft.Sharepoint.Client.Silverlight.dll and Microsoft.Sharepoint.Client.Silverlight.Runtime.dll from my Sharepoint 2010 server to my development machine (without Sharepoint). I assumed the Silverlight code I tested on the Sharepoint 2010 server would also work on my development machine. Naturally, I don't use the "ApplicationContext.Current.Url" because I am not executing in Sharepoint, so I manually add sharepoint server name as follows (kept anonymous for the post):
//ClientContext context = new ClientContext(ApplicationContext.Current.Url);
ClientContext context = new ClientContext("https://[servername]");
_web = context.Web;
context.Load(_web);
context.Load(_web.Lists);
context.ExecuteQueryAsync(new ClientRequestSucceededEventHandler (OnRequestSucceeded), new ClientRequestFailedEventHandler(OnRequestFailed));
When I execute the code, I am prompted by a Windows Authentication window (Sharepoint is configured to use Windows Authentication), I add my domain/user and password. However, I am getting the following error:
Note: I was able to get Sharepoint 2010 web services working given a similar error by changing the binding security mode="Transport" and including a clientAccessPolicy.xml file on the Sharepoint root website. Do I need to configure another Sharepoint directory for thje Client Object Model endpoint?
Exception {System.Security.SecurityException ---> System.Security.SecurityException: Security error.
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.b__4(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass2.b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryGetResponseAsyncCallback(IAsyncResult asyncResult)} System.Exception {System.Security.SecurityException}
Please look in to the below blog post, you need to add clientaccesspolicy.xml file in your sharepoint website root folder.
http://vangalvenkat.blogspot.com/2011/08/sharepoint-2010-getting-list-item.html
Aha, I found it. You can set the security on the client context to use the default windows authentication like so:
using (Microsoft.Sharepoint.Client.ClientContext ctx = new Microsoft.Sharepoint.Client.ClientContext("http://sharepointserver")){
ctx.AuthenticationMode = Microsoft.Sharepoint.Client.ClientAuthenticationMode.Default
}
This should also prevent any windows authentication pop-ups

Resources