【问题标题】:Why is my DTO Null?为什么我的 DTO 为空?
【发布时间】:2018-04-07 07:00:13
【问题描述】:

我正在从事的项目中有几个 DTO。我正在使用 AutoMapper 创建映射。除了其中一个之外,所有映射都有效。我可以知道,因为在使用 LINQ 方法语法检索数据时,我得到了 Null 引用。无论如何,这是我认为相关的所有代码:

MappingProfile.cs

using AutoMapper;
using GigHub.Controllers.Api;
using GigHub.Dtos;
using GigHub.Models;

namespace GigHub.App_Start
{
    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            Mapper.CreateMap<ApplicationUser, UserDto>();
            Mapper.CreateMap<Gig, GigDto>();
            Mapper.CreateMap<Notification, NotificationDto>();
            Mapper.CreateMap<Following, FollowingDto>();
        }
    }
}

Global.asax.cs

using AutoMapper;
using GigHub.App_Start;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace GigHub
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            Mapper.Initialize(c => c.AddProfile<MappingProfile>());
            GlobalConfiguration.Configure(WebApiConfig.Register);
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("elmah.axd");

        }

    }
}

Following.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace GigHub.Models
{
    // Alternatively, this class could be called Relationship.
    public class Following
    {
        [Key]
        [Column(Order = 1)]
        public string FollowerId { get; set; }

        [Key]
        [Column(Order = 2)]
        public string FolloweeId { get; set; }

        public ApplicationUser Follower { get; set; }
        public ApplicationUser Followee { get; set; }
    }
}

FollowingDto.cs

namespace GigHub.Dtos
{
    public class FollowingDto
    {
        public string FolloweeId { get; set; }    
    }
}

FollowingsController.cs

using System.Linq;
using System.Web.Http;
using GigHub.Dtos;
using GigHub.Models;
using Microsoft.AspNet.Identity;

namespace GigHub.Controllers.Api
{
    [Authorize]
    public class FollowingsController : ApiController
    {
        private ApplicationDbContext _context;

        public FollowingsController()
        {
            _context = new ApplicationDbContext();    
        }
            //CheckFollow is what I am using to test the Dto
        [HttpGet]
        public bool CheckFollow(FollowingDto dto)
        {
            var userId = User.Identity.GetUserId();
            if (_context.Followings.Any(f => f.FolloweeId == userId && f.FolloweeId == dto.FolloweeId))
                return true;
            else
                return false;

        }

        [HttpPost]
        public IHttpActionResult Follow(FollowingDto dto)
        {
            var userId = User.Identity.GetUserId();

            if (_context.Followings.Any(f => f.FolloweeId == userId && f.FolloweeId == dto.FolloweeId))
                return BadRequest("Following already exists.");

            var following = new Following
            {
                FollowerId = userId,
                FolloweeId = dto.FolloweeId
            };
            _context.Followings.Add(following);
            _context.SaveChanges();

            return Ok();
        }
    }
}

WebApiConfig.cs

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Web.Http;

namespace GigHub
{
    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}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

我怀疑这个工具是否重要,但我一直在使用 Postman 来测试我的 API。我在这个 Dto 中看到的与其他 Dto 的唯一区别是 Automapper 将为其创建映射的列在模型中具有 Key 和 Column Order 属性。我不明白为什么这很重要。我已经在网上搜索过这个问题,但解决方案没有帮助,因为我已经在做这些了。谁能从我发布的代码中看出为什么我可以获得 Null 引用?从技术上讲,Postman 中的错误是 System.Exception.TargetException,但据我了解,这意味着您的 LINQ 查询没有返回任何结果。

我知道我的查询有效,因为我传入了我的数据库中的字符串 FolloweeId 并且 API CheckFollow 操作有效。所以我只能假设我的 Dto 没有正确映射。

【问题讨论】:

    标签: c# asp.net linq nullreferenceexception dto


    【解决方案1】:

    我解决了自己的问题。我显然已经展示了我在 Web API 方面是多么的新手。无论如何,我将我的 CheckFollow 状态视为 POST 操作,但事实并非如此。这是一个 GET 操作。 GET 动作有什么? URL 中的参数。所以我只是简单地装饰了我的动作参数:

    public bool CheckFollow([FromUri] FollowingDto dto)
    

    这允许操作从 URL 中提取参数并传递给包含一个字符串类型属性的 Dto。 Dto 不再为空,我的操作有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-04
      • 2018-06-26
      • 2010-11-25
      • 2015-02-22
      • 2017-12-07
      • 2010-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多