的WebAPI控制器,可空(WebApi controller gives nulls)

2019-11-01 15:00发布

好吧,这里是我的路线

        Config.Routes.MapHttpRoute(
            name: "Default",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

而我的控制器

public class GameController : ApiController
{
    internal static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
    [HttpGet,HttpPost]
    public IEnumerable<HostedGame> List()
    {
        return new HostedGame[0];
    }

    [HttpPost]
    public Guid? HostGame(HostedGameRequest request)
    {
        try
        {
            var r = this.Request.Content.ReadAsStringAsync();
            var id = SasManagerHub.NextConnectionId;
            //var hg = request.ToHostedGameSasRequest();
            //GameManager.GetContext().SasManagerHub.Out.Client(id).StartGame(hg);
            //return hg.Id;
            return null;
        }
        catch (Exception e)
        {
            Log.Fatal("HostGame error",e);
            return null;
        }
    }
}

我的模型

public class HostedGame
{
    public Guid Id { get; set; }

    public string Name { get; set; }

    public string HostUserName { get; set; }

    public string GameName { get; set; }

    public Guid GameId { get; set; }

    public Version GameVersion { get; set; }

    public bool HasPassword { get; set; }
}

public class HostedGameRequest : HostedGame
{
    public string Password { get; set; }
}

和后数据

{
    "Id":"c883fb55-9adc-4ab8-a46c-614d2874301c",
    "Name":"a",
    "HostUserName":"b",
    "GameName":"c",
    "GameId":"c883fb55-9adc-4ab8-a46c-614d2874301c",
    "GameVersion":"1.1.1.1",
    "HasPassword":"true",
    "Password":"asdf"
}

和URL

http://localhost:5879/api/game/HostGame/

好吧,出于某种原因,当我抛在这些数据中,它使得在适当的行动GameController ,但参数request始终是null 。 我已经尝试了不少变化,但似乎无法使它发挥作用。

任何想法我可能做错了什么?

Answer 1:

请确保您传递头内容类型:应用程序/ JSON在您的文章的请求。



文章来源: WebApi controller gives nulls