Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

web services - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...