WebApi控制器提供空值

时间:2013-02-22 03:57:01

标签: c# post asp.net-web-api

好的,这是我的路线

        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"
}

以及网址

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

好吧,因此出于某些原因,当我将数据投入其中时,它会在GameController中执行适当的操作,但参数request始终为null。我尝试了很多变化,但似乎无法使其发挥作用。

我在这里做错了什么想法?

1 个答案:

答案 0 :(得分:1)

确保在帖子请求中传递标题content-type:application / json。