从控制台应用程序发布到Web API

时间:2014-01-25 03:56:29

标签: c# asp.net-mvc asp.net-web-api console-application

我无法从控制台应用程序向WebAPI发布字符串:

控制台应用:

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);
    }

我尝试在MVC4 Web应用程序中调用WebAPI:

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 = "p@p.pt", Message = "comment" });
            }
            catch(Exception e)
            {
                response = e.Message;
            }

            return response;
        }
    }
}

[编辑]

用fiddler测试后,我收到错误:

 {"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.

我不知道如何调试它,以及为什么它不起作用。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

以下是我的回答,Web API始终存在简单类型的问题。阅读Rick Strahls Blog Post on Web API problems with Simple Data Types

你能做什么,以这种方式拥有WEB API代码 -

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

让HttpClient以这种方式请求 -

    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);
    });

将输出如下 - enter image description here

[---基于问题编辑的编辑---]

我检查了最新的问题编辑和错误,因为没有默认构造函数。这个错误是因为您在构造函数注入时所做的依赖注入有问题。所以请检查那个区域。还可以使用Unity Web API依赖注入nuget来完成工作。 Here goes complete tutorial in setting up DI using Unity

另外请检查autofac是否需要MVC和Web Api的不同版本,至少Unity的情况如此。我认为您需要使用Autofac.WebApi 3.1.0 for DI来使用Web API控制器。

答案 1 :(得分:0)

首先,感谢所有的帮助。

问题是在我添加Api的MVC4项目中,我已经使用Autofac进行依赖注入,但我不知道我还需要DI用于ApiControllers。

所以我使用NuGet Autofac.WebApi 3.1.0安装并添加到Autofac Config行:

在开头:

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

最后:

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

现在一切正常! :)