Archive for category Error

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:

    $.ajax({
        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) {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                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
         GlobalConfiguration.Configure(WebApiConfig.Register);
     }

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

Advertisements

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:

[System.Web.Script.Services.ScriptService]
public class OdometerService : System.Web.Services.WebService {

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

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

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

Leave a comment

Showing MVC ModelState errors in the view

I wanted to show the various ModelState errors encountered in an MVC controller and display them in the view. So in my controller, I have a bit of code that loops through the errors and builds them in a string, adding an HTML line break between each error:

string errors = String.Empty;

foreach (ModelState modelState in ViewData.ModelState.Values) {
     foreach (ModelError error in modelState.Errors) {
          errors += “<br />” + error.ErrorMessage;
     }
}

ViewBag.Message = “The following errors have occurred: “ + errors;

In the view, I show my ViewBag variable. Notice that I use the Html.Raw method to display the HTML code properly in using Razor:

@Html.Raw(ViewBag.Message)

 

Leave a comment

Object doesn’t support property or method ‘autocomplete’

I’ve seen this message before and it usually occurs for one of two reasons:

1) The jquery-ui.js file (which is required to get autocomplete working) wasn’t included in the page
2) The script file that contains your implementation of autocomplete occurs BEFORE the jquery-ui.js file

So if I have the following code in the script.js file to attach the autocomplete code to a textbox:

$("#User").autocomplete({
    source: function (request, response) {
        if (request.length < 4) {
            return;
        }
        var customer = new Array();
        $.ajax({
            async: false,
            cache: false,
            type: "POST",
            url: "http://localhost:1234/MyController/Autocomplete",
            data: { "term": request.term },
            success: function (data) {
                for (var i = 0; i < data.length ; i++) {
                    customer[i] = { label: data[i].Value, Id: data[i].Key };
                }
            }
        });
        response(customer);
    },
    select: function (event, ui) {
        $("#UserId").val(ui.item.Id);
    }
});

Your web page or view with the autocomplete functionality should look something like this. Note our script file is after the jquery-ui.js file:

@model UserVM

@{
    ViewBag.Title = "Cool Page";
}

http://~/Scripts/jquery-ui.js
http://~/Scripts/script.js

@using (Html.BeginForm("UserStuff", "MyController")) {
 @Html.EditorFor(model => model.User)
}

Leave a comment

Invalid ModelState with a bound DropDownList

I had a simple model, like so:

    public class AmusementPark {
        public List<SelectListItem> Coasters { get; set; }
    }

I bound this simple model to a simple DropDownList, like so:

@Html.DropDownListFor(model => model.Coasters, Model.Coasters)

But when I submitted my model to the controller, I received an invalid ModelState. So I looked through the various errors in the ModelState with a bit of code:

    var errors = ModelState
        .Where(err => err.Value.Errors.Count > 0)
        .Select(err => new { err.Key, err.Value.Errors })
        .ToArray();

Lurking in the ModelState errors wasthis wonderful System.InvalidOperationException exception:

The parameter conversion from type ‘System.String’ to type ‘System.Web.Mvc.SelectListItem’ failed because no type converter can convert between these types.

Returning to the line in question, a DropDownList bound to a List of SelectListItem objects:

@Html.DropDownListFor(model => model.Coasters, Model.Coasters)

To resolve it, I first modified my model to have a key value:

    public class AmusementPark {
        public string CoasterId { get; set; }
        public List<SelectListItem> Coasters { get; set; }
    }

Then I modified the view to set the new CoasterId as the first parameter in my DropDownListFor helper:

@Html.DropDownListFor(model => model.CoasterId, Model.Coaster)

Voila, the ModelState was now valid when posting.

,

Leave a comment

The Entity Framework provider type… exception when unit testing

While merrily going about my business creating an MVC project using Entity Framework 6 against an Oracle database, I decided that unit testing my data layer would be a fun, useful thing to do. So I added a reference to my MVC project into my unit test project and away I went. But not too far because I got this error:

{System.InvalidOperationException: The Entity Framework provider type ‘Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342’ registered in the application config file for the ADO.NET provider with invariant name ‘Oracle.ManagedDataAccess.Client’ could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application.

This was thankfully an easy issue to correct. In my unit test project, I added references to the Oracle.ManagedDataAccess and Oracle.ManagedDataAccess.EntityFramework DLLs, and I was testing like a madman.

Leave a comment

An exception of type ‘System.TypeInitializationException’ occurred

I was running code that called a static class, Repository, to populate an Application variable, like so:

Application["UserTypes"] = Repository.PopulateUserTypes();

When I did this, I received the following error:

 An exception of type 'System.TypeInitializationException' occurred in ScottApp.dll but was not handled in user code

The InnerException property was not terribly helpful:

Object reference not set to an instance of an object.

Turns out it was because I had forgotten to add a connection string, “ScottConn”, to the web.config. The static Repository class was attempting to reference this missing property when it loaded:

private static string connString = ConfigurationManager.ConnectionStrings["ScottConn"].ConnectionString;

Adding this missing string to the web.config file, the error disappeared.

Leave a comment