Archive for category .NET

401 – Unauthorized in an ASP.NET project

While debugging a new to me (I didn’t write it) ASP.NET project locally, I came across this error when the default.aspx page loaded:

401 - Unauthorized: Access is denied due to invalid credentials.
You do not have permission to view this directory or page using the credentials that you supplied.

There are several reasons why this could happen, but in my case, it was because the application was set to reject unauthenticated users. In the web.config file, there was this section:

      <deny users="?" />

Disabling the <deny> tag resolved the issue.


Leave a comment

Web API getting 404

When trying to perform a simple GET request using Web API in my MVC application, I was getting a 404 message. I was accessing it through Ajax, and the URL was correct:

        url: 'http://localhost:1234/api/UserApi',
        type: 'GET',
        cache: false,
        contentType: 'application/json'

The problem was actually environmental. At a particular job site, the machines were locked down, including not being able to run PowerShell command – thus, an impediment to using NuGet. So I had to do several things to get my project working, but hopefully, if you’re having a similar issue, one of these is the key for you.

Several DLLs needed to be replaced, as the version were too old:

  • System.Net.Http
  • System.Net.Http.Formatting
  • System.Web.Http

The WebApiConfig.cs file was missing from the App_Start folder, so I added it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace ScottProject.App_Start {
    public class WebApiConfig {
        public static void Register(HttpConfiguration config) {

                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }

The Global.ascx.cs file was missing the referene to the WebApiConfig file:

     protected void Application_Start() {
         // Other file snipped out

So this particular situation was specific to my situation, but perhaps one of those issues will help someone else.

Leave a comment

Calling a .NET web service using jQuery

I was attempting to call a .NET web service using jQuery, but was getting this error message:

An attempt was made to call the method \u0027GetCoasters\u0027 using a GET request, which is not allowed

The key to fixing this was to attach the “ScriptMethod” attribute to the web service and setting the “UseHttpGet” property to “true”, which I show below:

public class OdometerService : System.Web.Services.WebService {

        [System.Web.Script.Services.ScriptMethod(UseHttpGet = true, 
              ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
        public string GetCoasters() {
            return "Hello World";

And here is me calling the web service – try to contain your excitement:

 type: "GET",
 url: "http://localhost:12345/CoasterService.asmx/GetCoasters",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (msg) {
 }, error: function (e) {
      alert('Bad stuff - ' + e.responseText);

Leave a comment

Passing a list of numbers into an Oracle procedure

I wanted to pass in a list of numbers to an Oracle procedure for use in an “IN” statement, called from C# code. First, the C# code:

  string list = "1,2,3";
  using (OracleCommand comm= new OracleCommand("MyProcedure", connection)) {
     comm.CommandType = CommandType.StoredProcedure;
     comm.Parameters.Add(":pList", OracleDbType.Varchar2, 50).Value = list;
     comm.Parameters.Add(":p_cursor", OracleDbType.RefCursor).Direction = ParameterDirection.Output;

My Oracle procedure was equally awesome:

    PROCEDURE MyProcedure(pList IN VARCHAR2, p_cursor OUT sys_refcursor) IS
        OPEN p_cursor FOR
            SELECT name 
            FROM coasters
            WHERE id IN (SELECT TO_NUMBER(column_value) AS IDs FROM XMLTABLE(pList));

You can see the “FROM XMLTABLE” statement is doing all the good stuff of splitting the list into the appropriate format. Good times.

Leave a comment

Encrypting the connection string for Entity Framework

I needed to encrypt the connection string that Entity Framework uses for its magic. So I encrypted the value in the “connectionString” attribute:

   <add name="ConnString" connectionString="x4eAeGmvVTwzSOE2js7oWjQgdf" 
      providerName="System.Data.EntityClient" />

I then updated the class in my application that is derived from the DbContext class, decrypting (using the creatively named “ScottsDecryption” (and no, that’s not the actual name)) the string in the call to “base”:

public partial class Entities : DbContext {
   public Entities()

       : base(ScottsDecryption(ConfigurationManager.ConnectionStrings["Entities"].ConnectionString)) { }

By the way, I received a ‘Keyword not supported: “data source”‘ error when first trying to get this working. I needed to replace the “&quot;” entries with actual single quote marks in the connection string, as described in this Stack Overflow post. So I had to change this connection string:

metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.SRModel.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string=&quot;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=blah)(PORT = 1234))(CONNECT_DATA=(;User Id=MyID;Password=nope;&quot;

To this:

metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.SRModel.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string='Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=blah)(PORT = 1234))(CONNECT_DATA=(;User Id=MyID;Password=nope;'

Leave a comment

HttpContext.Current.Session is null in web service

I was working with an web service (the old school .asmx kind), and I was encountering an issue where my Session object was null. Not a particular Session variable – all Session objects. When I would try to reference the following line, I was getting the “Object reference not found” message when I hovered over the “Session” part of the line in the debugger:

Session["Result"] = result;

To get around this, I added the “EnableSession” to true in the WebMethod attribute:

    [WebMethod(EnableSession = true)]
    public string RegisterNewUser(string bname, string first, string last) {
       // Do stuff

Leave a comment

Empty string returned from long Oracle text field

I was returning data from an Oracle procedure using an OracleDataAdapter. I noticed that one text field that can hold large values was returning an empty string. So in the following, the “description” value was empty, when I knew the “ParkDescription” field in the database had a value:

string description = ds.Tables[0].Rows[0]["ParkDescription"].ToString();

Running the query in Toad, I could see the data was there. To resolve this, I needed to set the InitialLONGFetchSize  propety of the data adapter’s SelectCommand object to -1:

OracleDataAdapter adp = new OracleDataAdapter(comm);
adp.SelectCommand.InitialLONGFetchSize = -1;

Leave a comment