简体   繁体   English

发布到Web API

[英]Posting to web api

What would be the best or better way to handle posting to a web api and how would it be done via C#? 处理发布到Web api的最好或更好的方法是什么,如何通过C#完成?

Web API code 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;}
}

Code to call web api 调用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);

This returns a 500 internal server error. 这将返回500内部服务器错误。 Is there something missing here? 这里缺少什么吗?

Web API config 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 }
        );

    }
}

Have you tried this: add the FromBody attribute to your model and post a model that matches m in the body 您是否尝试过:将FromBody属性添加到模型中并发布与主体中的m匹配的模型

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

Changing the routing code to include the action fixed the issue. 更改路由代码以包括该操作可解决此问题。 It looks like the code to call the web API worked fine so long as their was one GET or POST method as any call would try to use one of those. 只要它们是一种GET或POST方法,调用Web API的代码就可以正常工作,因为任何调用都将尝试使用其中一种。

Without the action it did not know which method to use in the API controller as it could not route to it. 如果没有该操作,它将不知道在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 }
        );
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM