处理发布到web的最好或更好的方式是什么?如何通过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 }
);
}
}发布于 2019-03-12 02:20:38
您是否尝试过这样做:将FromBody属性添加到模型中,并在主体中发布一个与m匹配的模型
[HttpPost]
public IHttpActionResult ApiPost([FromBody] Model m)
{
return Ok();
}发布于 2019-03-12 02:36:19
更改路由代码以包含操作已修复此问题。只要是一个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 }
);
}https://stackoverflow.com/questions/55107505
复制相似问题