MVC WebApi HttpGet与复杂对象 [英] MVC WebApi HttpGet with complex object

查看:61
本文介绍了MVC WebApi HttpGet与复杂对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的WebApi操作,我想从HttpPost切换到HttpGet.当前,它需要一个复杂的对象作为参数.

I have an existing WebApi action, that I want to switch from HttpPost to HttpGet. It currently takes a single complex object as parameter.

模型:

public class BarRequest
{
    [JsonProperty("catid")]
    public int CategoryId { get; set; }
}

控制器:

public class FooController : ApiController
{
    //[HttpPost]
    [HttpGet]
    [ActionName("bar")]
    public void Bar([FromUri] BarRequest request)
    {
        if (request != null)
        {
            // CategoryId should be 123, not 0
            Debug.WriteLine("Category ID :: {0}", request.CategoryId);
        }
    }
}

现在,当我发送以下请求时,一切都会按预期进行.

Now when I send the following request, everything works as expected.

GET /foo/bar?CategoryId=123

旧的POST请求也按预期工作.

Also the old POST request worked as expected.

POST /foo/bar {"catid":123}

但是现在我需要以下请求才能工作:

But now I need the following request to work:

GET /foo/bar?catid=123

我该怎么做?

推荐答案

感谢您的建议,但对我而言唯一可行的解​​决方案如下.

Thanks for suggestions, but the only solution that works for me, is the following.

之前:

var data = {
    catid: 123,
    // <snip>
};
var json = JSON.stringify(data);
$.post('/foo/bar', json, callback);

public class FooController : ApiController
{
    [HttpPost, ActionName("bar")]
    public void Bar(BarRequest request)
    {
        // use request.Category to process request
    }
}

之后:

var data = {
    catid: 123,
    // <snip>
};
var json = JSON.stringify(data);
$.get('/foo/bar?data=' + encodeURIComponent(json), callback);

public class FooController : ApiController
{
    [HttpGet, ActionName("bar")]
    public void Bar(string data)
    {
        var request = JsonConvert.DeserializeObject<BarRequest>(data);
        // use request.Category to process request
    }
}

这样,我无需触摸客户端或服务器上的任何模型,验证器等.另外,所有其他解决方案都要求我在服务器或客户端上更改命名约定.

This way I don't need to touch any model, validator, etc. on the client or server. Additionally every other solution required me to change the naming conventions on either the server or the client side.

这篇关于MVC WebApi HttpGet与复杂对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆