WebApi POST参数始终为null

时间:2015-08-15 10:10:02

标签: c# json breeze asp.net-web-api

我正在尝试设置一个webapi方法,我可以使用该方法将用户添加到我的数据库中。 在前端,我使用木偶骨干和breezejs来保存对我的webapi的更改。

我的后端有一个实体,用户看起来如下:

public class ApiUserEntity {
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public DateTime CreatedAt { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string Email { get; set; }
    public ApiPermission Permission { get; set; }
    public ApiUserRole Role { get; set; }
}

2个枚举看起来像这样:

public enum ApiUserRole {
    User,
    Staff,
    Admin,
    Master
}

public enum ApiPermission {
    Read,
    Write,
    ReadWrite,
    None
}

当我尝试添加(注册)用户时,发布的实体始终为null。 Posted entity is null 但正如您在屏幕截图中看到的那样,我通过以下方式观看发布值:

base.Request.Content.ReadAsStringAsync().Result

我只能将发布的json值看作字符串。

 
{"Id":-1,"CreatedAt":"1899-12-31T23:00:00","Username":"test","Password":"test","Email":"test@test.nl","Permission":"3","Role":"0"}

它似乎与对象的反序列化有关。 我看着提琴手看看它是否设置了正确的内容类型:

--batch_7273 - bef2 - 5778
Content - Type: multipart / mixed; boundary = changeset_9a18 - de60 - f7a4

--changeset_9a18 - de60 - f7a4
Content - Type: application / http
Content - Transfer - Encoding: binary

POST / odata / ApiUsers HTTP/ 1.1
Content - ID: 1
DataServiceVersion: 2.0
Accept: application / atomsvc + xml; q = 0.8, application / json; odata = fullmetadata; q = 0.7, application / json; q = 0.5, */*;q=0.1
Content-Type: application/json
MaxDataServiceVersion: 3.0

{"Id":-1,"CreatedAt":"1899-12-31T23:00:00","Username":"test","Password":"test","Email":"test@test.nl","Permission":"3","Role":"0"}
--changeset_9a18-de60-f7a4--

--batch_7273-bef2-5778--

正如您所看到的那样,内容类型设置为该批处理项的application / json,但我的实体保持为空,看起来webapi无法将json转换为我的apiuserentity对象。

编辑我的路线注册如下:

 
 public static void Register(HttpConfiguration config)
{
    var cors = new EnableCorsAttribute("*", "*", "*", "DataServiceVersion, MaxDataServiceVersion"); // origins, headers, methods
    config.EnableCors(cors);

    config.DependencyResolver = new UnityDependencyResolver(UnityHelpers.GetConfiguredContainer());

    // enable elmah
    config.Services.Add(typeof (IExceptionLogger), new ElmahExceptionLogger());

    // Web API routes
    config.MapHttpAttributeRoutes();

    ODataModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<ApiUserEntity>("ApiUsers");
    builder.EntitySet<DomainEntity>("Domains");
    builder.EntitySet<RouteEntity>("Routes");
    builder.EntitySet<ModuleEntity>("Modules");

    config.Routes.MapODataServiceRoute(
        routeName: "odata",
        routePrefix: "odata",
        model: builder.GetEdmModel(),
        batchHandler: new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer)
        );
}

EDIT2: 当webapi动作被击中时,我已经跟踪了例外情况并发现了这一点:

 iisexpress.exe Information: 0 : Request, Method = POST, Url = http://localhost:22594/odata/ApiUsers, Message='http://localhost:22594/odata/ApiUsers'
iisexpress.exe Information: 0 : Message = 'ApiUsers', Operation = DefaultHttpControllerSelector.SelectController
iisexpress.exe Information: 0 : Message = 'WebAPI.Controllers.ApiUsersController', Operation = DefaultHttpControllerActivator.Create
iisexpress.exe Information: 0 : Message = 'WebAPI.Controllers.ApiUsersController', Operation = HttpControllerDescriptor.CreateController
iisexpress.exe Information: 0 : Message = 'Selected action 'Post(ApiUserEntity apiUserEntity)'', Operation = ApiControllerActionSelector.SelectAction
iisexpress.exe Information: 0 : Message = 'Selected action 'Post(ApiUserEntity apiUserEntity)'', Operation = ODataActionSelector.SelectAction
iisexpress.exe Information: 0 : Message = 'Will use new 'ODataMediaTypeFormatter' formatter', Operation = ODataMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message = 'Will use new 'ODataMediaTypeFormatter' formatter', Operation = ODataMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message = 'Will use new 'ODataMediaTypeFormatter' formatter', Operation = ODataMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message = 'Will use new 'ODataMediaTypeFormatter' formatter', Operation = ODataMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message = 'Will use new 'ODataMediaTypeFormatter' formatter', Operation = ODataMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message = 'Will use new 'ODataMediaTypeFormatter' formatter', Operation = ODataMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message = 'Will use new 'ODataMediaTypeFormatter' formatter', Operation = ODataMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message = 'Will use same 'FormUrlEncodedMediaTypeFormatter' formatter', Operation = FormUrlEncodedMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message = 'Will use same 'JQueryMvcFormUrlEncodedFormatter' formatter', Operation = JQueryMvcFormUrlEncodedFormatter.GetPerRequestFormatterInstance
iisexpress.exe Error: 0 : Operation = ODataMediaTypeFormatter.ReadFromStreamAsync, Exception = System.NotImplementedException: the method or operation is not implemented

at System.Web.HttpContextBase.get_Response()
at System.Web.UI.Util.GetUrlWithApplicationPath(HttpContextBase context, String url)
at System.Web.Routing.RouteCollection.NormalizeVirtualPath(RequestContext requestContext, String virtualPath)
at System.Web.Routing.RouteCollection.GetVirtualPath(RequestContext requestContext, String name, RouteValueDictionary values)
at System.Web.Http.WebHost.Routing.HostedHttpRouteCollection.GetVirtualPath(HttpRequestMessage request, String name, IDictionary`2 values)
at System.Web.Http.Routing.UrlHelper.GetVirtualPath(HttpRequestMessage request, String routeName, IDictionary`2 routeValues)
at System.Web.Http.Routing.UrlHelper.Route(String routeName, IDictionary`2 routeValues)
at System.Web.Http.Routing.UrlHelper.Link(String routeName, IDictionary`2 routeValues)
at System.Web.Http.OData.Extensions.UrlHelperExtensions.CreateODataLink(UrlHelper urlHelper, String routeName, IODataPathHandler pathHandler, IList`1 segments)
at System.Web.Http.OData.Extensions.UrlHelperExtensions.CreateODataLink(UrlHelper urlHelper, IList`1 segments)
at System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.GetBaseAddress(HttpRequestMessage request)
at System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)

EDIT3:我已经将我的控制器类型更改为apicontroller而不是odatacontroller,现在它突然起作用了。我想使用odatacontroller

1 个答案:

答案 0 :(得分:0)

很少有事情要检查:

  1. 日期字段正在反序列化。
  2. 尝试分配您的Enums int值,并将JSON值作为int而不是字符串传递。
  3. 您是否应该为您的身份证件传递-1?将此字段保留为null,如果由DB填充,则由DB填充。