发布到Web API

时间:2019-03-11 17:41:34

标签: c# .net dotnet-httpclient

处理发布到Web api的最好或更好的方法是什么,如何通过C#完成?

Web API代码

public class ProcessController : ApiController
{
    [HttpGet]
    public string Test()
    {
        return "Hello from API";
    }


    [HttpPost]
    public IHttpActionResult ApiPost(Model m)
    {
        return Ok();
    }
}

public class Model
{
    public int Id {get; set;}
    public string Name {get; set;}
}

调用Web API的代码

HttpClient client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true });
client.BaseAddress = new Uri("http://localhost:2478/api/Process/");

HttpResponseMessage response = await client.GetAsync("test");

Model m = new Model ();
m.Id= 4;
m.Name = "test";

var r = client.PostAsJsonAsync("ApiPost", m);

这将返回500内部服务器错误。这里缺少什么吗?

Web API配置

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var settings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
        settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        settings.Formatting = Formatting.Indented;

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

    }
}

2 个答案:

答案 0 :(得分:1)

您是否尝试过:将FromBody属性添加到模型中并发布与主体中的m匹配的模型

[HttpPost]
public IHttpActionResult ApiPost([FromBody] Model m)
{
    return Ok();
}

答案 1 :(得分:1)

更改路由代码以包含该操作可解决此问题。只要它们是一种GET或POST方法,调用Web API的代码就可以正常工作,因为任何调用都将尝试使用其中一种。

没有动作,它不知道在API控制器中使用哪种方法,因为它无法路由到它。

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional }
        );
    }