使用接口作为数据协定发布到Web API

时间:2013-07-26 19:34:39

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

我有以下APi控制器

public class TriggerController : ApiController
    {
        [HttpPost]
        [ActionName("fileimport")]
        public int CreateFileImportTrigger([FromBody]ITrigger _object)
        {
            return scheduler.CreateFileImportTrigger(_object);
        }
.....
...

我的WEbApiConfig是这样的,并且呼叫与第三条路线匹配。

  public static void Register(HttpConfiguration config)
        {

        config.Routes.MapHttpRoute(
        name: "ApiById",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional },
        constraints: new { id = @"^[0-9]+$" }
        );





config.Routes.MapHttpRoute(
            name: "ApiByName",
        routeTemplate: "api/{controller}/{action}/{name}",
        defaults: null,
        constraints: new { name = @"^[a-z]+$" }
    );

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

    var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
    config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

}

ITrigger定义如此。

public interface ITrigger
{
    string Name{ get; set; }
    string FilePath{ get; set; }
    string TriggeredJobEntityCode{ get; set; }
    int ID{ get; set; }
    TriggerTypes Type{ get; set; }
    string SubmitDate{ get; set; }
    DateTime SubmitTime{ get; set; }
    IJob[] Jobs { get; set; }

}

我已在Http Header中指定Content-Type为application / json

我发布的身体就是这样

{
    "Name": "FileEventTrigger",
    "FilePath": "C:\\Users\\file.txt",
    "TriggeredJobEntityCode": null,
    "Jobs": [
        {
            "ID": 1643,
            "TemplateID": 1643,
            "Name": "SomeJob",
            "SubmitToRunTime": "0001-01-01T00:00:00",
            "Parameters": [
                {
                    "Name": "Seconds",
                    "Value": "30",
                    "DefaultValue": "30",
                    "isRequired": true,
                    "DataType": "Integer"
                }
            ]
        }
    ],
    "ID": 1,
    "Type": 0,
    "SubmitDate": "7/21/2013",
    "SubmitTime": "0001-01-01T00:00:00"
}

我在CreateFileImportTrigger方法的开头有一个断点,我检查_object的值,并在发布调用后显示“null”。所以某处WebApi应用程序不读取正文并将其序列化为_object参数。该服务正在返回ITrigger对象,但无法处理POST。

任何帮助将不胜感激。

由于

0 个答案:

没有答案