Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the "no type was found that matches the controller named" error message during Ajax Request

I've seen a lot of topics about this, but unfortunately I believe that each case is a different case (or most of them), and I really would love some experts opinion about my case in particular since I cannot make my code work even after reading through some of the other topics.

Situation: I am using an Ajax Request call in jQuery to a WebService method I have created in an WebApi project together with a MVC 4 Application.

My WebService controller class looks like the default, like this:

public class AdditionalInfoController : ApiController
{
    //GET api/AdditionalInfo
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    //GET api/AdditionalInfo/5
    public string Get(int id)
    {
        return "value";
    }

    //PUT api/AdditionalInfo/5
    public void Put(int id)
    {
        string test = "";
    }
}

My Ajax Request from jQuery looks like this:

function GetAdditionalInfo(obj)
{
    var request = jQuery.ajax({
        url: "/api/AdditionalInfo/Get",
        type: "GET",
        data: { id: obj.id },
        datatype: "json",
        async: false,
        beforeSend: function () {
        },
        complete: function () {
        }
    })
    .done(function (a,b,c) {
        alert("Additional info was retrieved successfully!");
    })
    .fail(function (a,b,c) {
        alert("An error happened while trying to get the additional info!");
    });
}

My WebAPIConfig file looks like this:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

And last but not least, this is my problem: this error message keeps appearing when I browse the returned data variable in .fail and this is what is written:

"{
    "Message":"No HTTP resource was found that matches the request URI      'http://localhost:59096/api/AdditionalInfo/Get?id=1'.",
    "MessageDetail":"No type was found that matches the controller named    'AdditionalInfo'."
}"

I would really appreciate it if someone could help me as soon as possible. Thanks in advance!

Best regards,
Mad

like image 786
MadGatsu Avatar asked May 21 '13 15:05

MadGatsu


2 Answers

Looking at the error looks like Web API is unable to find the controller 'type' AdditionalInfo. Web API uses assemblies resolver to scan through the assemblies and finds out the controller types. In your case for some reason its unable to find your 'AdditionalInfo' controller probably because it has some problem loading the assembly having this controller.

Try the following and see if there are any errors logged in your EventLog. If you notice any errors then probably you should check if your controllers are present in those assemblies.

  • Make the following change in Web.config to view errors in EventLog

    <system.diagnostics> <trace autoflush="false" indentsize="4"> <listeners> <add name="myListener" type="System.Diagnostics.EventLogTraceListener" initializeData="WebApiDiagnostics" /> </listeners> </trace> </system.diagnostics>

  • In your WebApiConfig.cs, you can do the following:

       IAssembliesResolver assembliesResolver = config.Services.GetAssembliesResolver();
    
        ICollection<Assembly> assemblies = assembliesResolver.GetAssemblies();
    
        StringBuilder errorsBuilder = new StringBuilder();
    
        foreach (Assembly assembly in assemblies)
        {
            Type[] exportedTypes = null;
            if (assembly == null || assembly.IsDynamic)
            {
                // can't call GetExportedTypes on a dynamic assembly
                continue;
            }
    
            try
            {
                exportedTypes = assembly.GetExportedTypes();
            }
            catch (ReflectionTypeLoadException ex)
            {
                exportedTypes = ex.Types;
            }
            catch (Exception ex)
            {
                errorsBuilder.AppendLine(ex.ToString());
            }
        }
    
        if (errorsBuilder.Length > 0)
        {
            //Log errors into Event Log
            Trace.TraceError(errorsBuilder.ToString());
        }
    

    BTW, some of the above code is actually from the DefaultHttpControllerTypesResolver which Web API uses to resolve the controller types. http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Http/Dispatcher/DefaultHttpControllerTypeResolver.cs

Edited: One more scenario where you could hit this problem is if your controller is nested inside another class. This was a bug which was fixed later though.

like image 158
Kiran Avatar answered Nov 12 '22 17:11

Kiran


Ok, so I believe I found out what was going on. I am not entirely certain, but at least my problem got fixed.

Simply by changing what was inside of the "data" field in the Ajax call and I have created a class for an object in the application to hold the whole data. It seems that for some reason the method could not have the syntax "Get(int ID)".

Instead, I did something like "Get( object)" and in the Ajax Request something like "data: obj.ID" and voila, it worked.

Also, since the framework is picky about the names of the REST methods (Get, Post, Put and Delete), I changed the name of the method to something else (like Retrieve or something).

Hopefully this will help someone in the future as well.

Best regards,
Mad

like image 33
MadGatsu Avatar answered Nov 12 '22 19:11

MadGatsu