External HTTP requests from MVC application fail - asp.net-mvc

I'm having problems making HTTP requests from my MVC.Net Intranet application. I encountered the problem when using the RestSharp library, but have boiled it down to a much simpler repro.
The following code:
using (var client = new WebClient())
{
var contents = client.DownloadString("http://www.google.com");
}
Will run successfully (on my local machine, debugging from Visual Studio 2013) inside a console app.
Will run successfully (on my local machine) from within LinqPad
Times out (on my local machine, debugging from Visual Studio 2013, hosted with IIS Express) when run from a controller action in a MVC intranet app.
This may be a duplicate of Not able to connect to website URLs from Asp.Net WebApi Action Methods (and is where I got the boiled down proof-of-problem code above) but in my case this is all running locally on my computer and it works fine from a console app.
I've tried various different code snippets, including using HttpClient instead of WebClient:
using(System.Net.Http.HttpClient c = new System.Net.Http.HttpClient())
{
var msg = c.GetAsync("http://www.google.com").Result.Content.ReadAsStringAsync().Result;
}
But I get the same, or similar results and errors in all cases. For the code above, I eventually get a 'TaskCancelled' exception, with no Inner Exception.
I've also got colleagues to try the same on their own machines, with the same results. I have read some similar questions, where people talk about problems with deadlock due to the SyncronizationContext in ASP applications, but that seems to relate to asynchronous calls. Here, as far as I can tell, everything I am doing is synchronous so I can't see how that applies.
In reality, I'm using the RestSharp library, which I've used to create a client library of my own for talking to the facebook API. I had tested this from a console app test-harness, which worked perfectly, but it all times out when I start using it inside my MVC app.
Has anyone seen this before and have any ideas on where I'm going wrong, or what the issue might be?
Is it to do with locking / deadlocking?
Could it be to do with permissions / proxy? We have quite strict web proxy rules at work, which are obviously configured correctly for my user. Could IIS Express hosting be changing the permissions or the user assigned to the app? The IIS Express service is running with my username at present.
UPDATE
I have tinkered some more and tried accessing an internal company web page instead of an external page (Google). I find that this works immediately - so that suggests strongly that it's to do with permissions or proxy settings.
Can anyone explain why this would be different between a console app and a MVC application?
UPDATE 2
I've run Fiddler to check the request and see what was happening to it. When fiddler is running the request succeeds.
This makes me think it's some strange permissions issue possibly? As a security measure, our login accounts don't have admin rights, instead we have a separate non-interactive account with admin permissions we can use to run apps that need admin rights, or install software etc. To get fiddler to capture traffic, I have to run it with this account.
Still, the calls work fine with my own normal account from the console app or LinqPad - so I guess my question becomes:
For an asp / MVC app locally hosted via IIS Express (Visual Studio Debugging), what user will this be run as, and what differences (if any) would there be to a console app?

Related

404 error on azure for Asp.Net Web Api Project

I have deployed exact same solution on two servers, one is my own server in my basement and the other one is Microsoft Azure. The project is developed using Asp.Net Web Api 2.
On my own windows server running IIS 8.5 it totally works. For test, you can simply browse this link in your browser and see the error message {"Message":"The requested resource does not support http method 'GET'."} which shows the API has been hit.1
But exact same project on my Azure domain here, you just get a message saying
The resource you are looking for has been removed, had its name
changed, or is temporarily unavailable.
Everything about these two deployments is the same (to the best of my knowledge) and I was wondering if there is any further steps necessary on Web Api app deployment in MS Azure which I am missing.
I finally found the answer to this issue. If there are multiple apps deployed as one single website so each app is located in its own subfolder, you have to go to the configuration section of your web app on Azure and create virtual directories for each of those sub folders.
Ah, my problem was probably a common one. I was using
rootconfig = System.Web.Configuration.WebconfigurationManager.OpenWebConfiguration(null);
and that was returning the root web because the parameter was null.
When I ran it local that worked fine, but after I deployed the root Config was NOT what I wanted and my code was failing.
Switched to direct access via
stringVal = WebconfigurationManager.AppSettings["Foobar"].ToString();
Nice. Plus less overhead.

Reading pst (Outlook) files from IIS ASP.NET application

I have to create sort of a .PST file based Web Mail.
I need to read all MailItems, Folders, Contacts and everything i can from PST files given by the user.
I am currently using DCOM interop to create a Application and use Session to add my file's stores.
My problem is that i can't even instantiate the Outlook.Application, the code simply doesn't run.
If i change to Visual Studio Development Web Server everything works as perfectly as expected, but if i change to local IIS Web Server.. nothing happens =/
What i did so far:
Set username and pass to impersonate on web.config
Set username and pass to inpersonate on my WebSite from iis -> Authentication -> ASP.NET impersonation
Added permissions to Everyone, Network Service, IIS_IUSRS, my user account in temp asp files, web site file and pst files i'm trying to read
Unfortunately I've already implemented all I need using TDD, so it would not be a good idea to change the way i'm doing this, like moving to NMapi or something.
Thanks in advance
EDIT:
As i've mentioned before, i I cannot use another library (and that one seems to work, but it's pretty expensive).
I only need this to run on a local server. It is a Web application, but for localhost ONLY.
It is not a good idea to use Outlook on the server side, as is described in detail here: http://support.microsoft.com/kb/257757
Microsoft does not currently recommend, and does not support,
Automation of Microsoft Office applications from any unattended,
non-interactive client application or component (including ASP,
ASP.NET, DCOM, and NT Services), because Office may exhibit unstable
behavior and/or deadlock when Office is run in this environment.
Maybe have a look at http://www.independentsoft.de/pst/

Routing problem with particular controller name using ASP.NET MVC 1 in IIS 7

I have joined a team developing an ASP.NET MVC version 1 application. I run this app on my local machine using IIS version 7.5. My operating system is Windows Server 2008 R2 Enterprise Edition. I use Visual Studio 2008 SP1 for development.
One of the controllers in this app is called ReportsController. The route table entries for this controller use 'Reports' as the controller name part. The problem I have is that, using IIS 7.5 on my local machine, I simply cannot access any of the Reports action methods. If I try to access, say, '/Reports/Index' from Chrome or Firefox, I get a 401 Unauthorized response (as seen using Fiddler) and the browser displays its username/password entry dialog.
Please note the following:
All other non-Report pages in the application work correctly.
If I add a breakpoint to Application_BeginRequest, it is not hit when requesting a Reports page.
If I change the Reports routing entries in the route table registration code so that I have to access paths like '/Reportss/Index' (note the extra 's') then these Reports pages work correctly.
I have tried deleting then recreating my Web application in IIS.
The Reports pages work fine if I run the application using the Visual Studio 2008 development server (Cassini).
There is no directory called Reports in the application directory.
The Reports pages work correctly on our UAT environment, also under IIS 7.5.
I have reviewed my IIS setting several times, including comparing them with those on UAT, and I can't see a problem.
While I can use Cassini to access the Reports pages, I would really like to understand what is causing this issue.
If you have Reporting Services installed on your machine. try to create a new web site and use it. If you have SSRS installed on your machine it uses /reports for hosting reports.
I have had problems using the directory name 'Reports' at the root of a .net 2.0 website on IIS 7.5. It generates a 503 Error, indicating that there is an error at the system level before IIS tries to serve the page. I am not sure if reporting services is installed on my server. I just changed the directory name, all links and everything worked.
I have the exact same issue in my MVC Application with reporting services installed on the same server where code was deployed. I have changed the Reporting Manager URL in "SQL Server Reporting Services Configuration" which was hostName/Reports and assigned a new name i.e. SSRSReports so the virtual directory is now hostName/SSRSReports.
Now my application as well as SSRS Reports are working as expected.

Asp.net mvc application deployment / security issues

I'll start with appologies; I wasn't sure if this was best posted here of Server Fault so if its in the wrong place then please move :-)
Basic information
I have written the first module of a new application at work. This is written using Visual Studio 2010, targetting .net 3.5 (at the moment) and asp.net mvc 2. This has been working fine during development running on the built in Development server from VS but however does not work once deployed to IIS 7/7.5.
To deploy the application, I have built it in release mode and created a deployment package by right clicking on the project in the solution explorer (this will be done with an automated build in tfs once upgrade from the beta). This has then been imported into IIS on the server.
The application is using windows/domain authentication.
Issue #1
I can fire up internet explorer and browse to the application from a client computer as well as on a remote desktop connection. I can execute the code which reads/stores data in Session fine from the IE instance on the remote desktop but if I browse to it from the client pc it seems to lose the session state. I click on the form submit and the page refreshes and doesn't execute the required code. I've tried setting with; InProc, SQLServer and StateServer. but with no luck :-(
Issue #2
As part of the application it views PDF and Tiff documents on the fly which are on a network share on the office network and creates thumbnails if the document hasn't been viewed before. This works if running on the machine the application is deployed to; however when browsing from a client pc I get an error saying:
Access to the path '\\fileserver\folder\file.tif' is denied
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.UnauthorizedAccessException: Access to the path '\\fileserver\folder\file.TIF' is denied.
ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if the application is not impersonating. If the application is impersonating via , the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
As this is on a different server the user is not accessible. To get round this I have tried:
1 - setting the application pool to run as domain administrator (I know this is a security risk, but I'm just trying to get it to work at the moment!)
2 - to set the log on account for World Wide Web Publishing service to be the domain admin . When trying to restart the service I get ...
Windows could not start the World Wide Web Publishing Service service on the Local Computer.
Error 1079: The account specified for this service is different from the account specified fro the other services running in the same process.
Any pointers/help would be much appriciated as I'm pulling my hair out (of what little I have left).
Update
I've been using this funky little tool I found -
DelegConfig v2 beta (Delegation / Kerberos Configuration Tool). This has been really usefull. So I've got the accessing of the file share working (there is a test page which will read the files) so now I've just got the issue of passing through the users credentials through to the SQL Server (wans't my choice to do it this way!!) to execute the queries etc. but I can't get it to log on as the user. It tries to access it as "NT Authority\Network Service" which doesn't have a sql login (as should be the logged on user).
My connection string is:
<add name="User" connectionString="Data Source=.;Integrated Security=True" providerName="System.Data.SqlClient" />
No initial catalog is specified as the system is over multiple dbs (also wasn't my choice!!).
I really appriciate all the help so far! :-)
Any further hints?!
Issue #2 - Your options are:
Configure delegation (double-hop authentication) - I haven't done this on IIS7 and it's a bit different to 6, but I believe you will need to enable the web server machine account for delegation in AD, and create an SPN for the web server (eg setspn -A http/<Web Server FQDN> <Domain>\<Machine Name>). Troubleshooting Kerberos can be fairly painful.
Grant access to the network resources to the (domain) application pool account and make sure anonymous authentication is turned on ( <anonymousAuthentication enabled="true" userName="" defaultLogonDomain="" /> )
Response to Update:
You will need to make sure Kerberos authentication is working for SQL Server. Run the query select auth_scheme from sys.dm_exec_connections where session_id=##spid; it will return NTLM or KERBEROS. If it's NTLM, you'll need to do some work configuring SQL Server to use Kerberos. Set an SPN in AD for the SQL service account: setspn -A MSSQLSvc/<SQL Server FQDN>:1433 <Domain>\<Sql Service Account>, restart SQL Server and try the query again. You must use TCP/IP as the connection mechanism (this is the default).
If you don't have an initial catalog, you'll need to make sure that all of the user logins have a default database that they have access to. I would personally pick one database to be the initial catalog as you may get different behaviour depending on how the login is configured.
With this small part of information I could only give some hints:
Issue #1:
Maybe you have a misleading URL as action for the form? Or an caught&ignored exception? Do you have an onError-event in your global.asax.vb?
Sub Application_Error()
Dim ex As Exception = Server.GetLastError
' NOW HANDLE THE EXCEPTION --> REPORTING :-)
End Sub
Issue #2:
I recently had the same exception - I had to check the access-rights for users for this folder and set the appPool-identity to "NETWORKSERVICE". In your case you even try to access a network-folder - check the accessrights on the server and try to use the IP instead of the name - it could be a name-resolution-problem?!
Sorry for this small portion of information... This looks like problems only solveable with direct debug-options on the running server.
Finally last thing on Friday I got it working ...
As I said in the update, the tool for sorting out the delegation of credentials was very handy and helped no end to setting the correct SPN records.
I found I also had to set it up for SQL as I was passing through the credentials into the server. The other thing I found stopping the connections was some of the inbound windows firewall settings where causing problems.
For the connection string; I had to update to:
<add name="ConnectionStringName" connectionString="Data Source=.;Integrated Security=SSPI;Trusted_Connection=True" providerName="System.Data.SqlClient" />
Links I found useful:
Kerberos Authentication and SQL Server
DelegConfig
And even tho it mainly talks about Sharepoint ... this was also useful.
Hope this helps people in the future.

How do I get Visual Studio 2008's test web server to perform like IIS 7 or vice versa?

I have a mixed MVC and Web Forms environment that works just fine in VS2008 when I debug. However when I deploy the code to my staging environment I have issues.
Basically I'm using an old school URL Rewrite module for the old Web Forms app, so I have to run the App Pool in Classic Mode for the old URL Rewriter to work. However, when I do that I get 404 errors on my MVC stuff. But if I switch them to Integrated Mode my URL Rewriter doesn't work.
The real rub is that, like I said, both the old URL Rewrite module and the MVC stuff work just fine on the test web server you get when you debug in VS2008.
Is there a way to export to or mock those settings in IIS 7?
Another thing I guess I wouldn't mind would be to set up my Web Application on my local IIS so I can at least develop against the same settings and figure out what's breaking that way. But I'm not sure where I would begin there.
Steve Sandersons blog has a good description regarding setting IIS for mvc. Your problem might potentially have to do with handler mapping. Basically you need to map ".*" requests to "aspnet_isapi.dll" but see the blog for an in depth description.
EDIT: wrt the blog, I was referring to his option 1. He also has a few other suggestions.

Resources