WebApi controller gives nulls

拈花ヽ惹草 提交于 2019-12-25 09:40:12

问题


Ok here's my route

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

And my controller

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

And my Model

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

And the post data

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

And the URL

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

All right, so for some reason when I toss that data in, it makes it to the proper action in the GameController, but the argument request is always null. I've tried quite a few variations, but can't seem to make it work.

Any ideas what I may be doing wrong here?


回答1:


Make sure you are passing the header content-type:application/json in your post requests.



来源:https://stackoverflow.com/questions/15016563/webapi-controller-gives-nulls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!