Patrick
Patrick

Reputation: 2781

Post from Console Application to WebAPI

I'm unable to Post a string to a WebAPI from a Console Application:

Console App:

public void Main()
{
    try
    {
        ProcessData().Wait();
    }
    catch (Exception e)
    {
        logger.Log(LogLevel.Info, e);
    }
}

private static async Task ProcessData()
{
    try
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(API_BASE_URL);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // HTTP POST
            var response = await client.PostAsJsonAsync("api/teste", "test_api");
        }
    }
    catch (Exception e)
    {
        logger.Log(LogLevel.Info, e);
    }

I try to call a WebAPI in an MVC4 Web Application:

namespace Heelp.Api
{
    public class TesteController : ApiController
    {
        private readonly ICommentService _commentService;

        public TesteController(ICommentService commentService)
        {
            _commentService = commentService;
        }

        public string Post(string comment)
        {
            var response = "OK";

            try
            {
                _commentService.Create(new Core.DtoModels.CommentDto { CommentType = "Like", Email = "[email protected]", Message = "comment" });
            }
            catch(Exception e)
            {
                response = e.Message;
            }

            return response;
        }
    }
}

[EDIT]

After testing with fiddler, I get the error:

 {"Message":"An error has occurred.","ExceptionMessage":"Type 'Heelp.Api.TesteController' does not have a default onstructor",
    "ExceptionType":"System.ArgumentException","StackTrace":"   
        at System.Linq.Expressions.Expression.New(Type type)\r\n   at 
        System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at 
        System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, 
        HttpControllerDescriptor controllerDescriptor, Type controllerType)"}

The Route is the Default.

I don't know how to debug it, and why it's not working.

What am I doing wrong here?

Upvotes: 0

Views: 8931

Answers (2)

ramiramilu
ramiramilu

Reputation: 17182

Here goes my answer, Web API always had this problem with Simple Types. Read Rick Strahls Blog Post on Web API problems with Simple Data Types

What you can do it, have WEB API code in this way -

public HttpResponseMessage Post(FormDataCollection formData)
{
    return null;
}

And let HttpClient request in this way -

    HttpClient client = new HttpClient();
    var nameValues = new Dictionary<string, string>();
    nameValues.Add("Name", "hi");
    var Name = new FormUrlEncodedContent(nameValues);
    client.PostAsync("http://localhost:23133/api/values", Name).ContinueWith(task =>
    {
        var responseNew = task.Result;
        Console.WriteLine(responseNew.Content.ReadAsStringAsync().Result);
    });

that will give the output as follows - enter image description here

[--- EDIT based on question edit ---]

I checked the latest edit on question and the Error because of no Default Constructor. That error is because you got something wrong with Dependency Injection which you are doing for constructor injection. So please check that area. Also use Unity Web API Dependency Injection nuget to get the work done. Here goes complete tutorial in setting up DI using Unity.

Also please check the autofac if you need different versions of it from MVC and Web Api, at least that is the case with Unity though. I think you need to have Autofac.WebApi 3.1.0 for DI to work with Web API controllers.

Upvotes: 1

Patrick
Patrick

Reputation: 2781

First of all, thanks for all the help.

The problem was that in the MVC4 project where I add the Api, I was already using Autofac for Dependency Injection, but I was not aware that I also need DI for the ApiControllers.

So I installed using NuGet Autofac.WebApi 3.1.0 and add to the Autofac Config the lines:

In the Begin:

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

In the End:

GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

Now everything is working fine ! :)

Upvotes: 0

Related Questions