根据json值路由到不同的动作 [英] Route to different actions based on json value

查看:97
本文介绍了根据json值路由到不同的动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据特定json参数的值将请求路由到不同的操作.

I would like to route requests to different actions based on the value of a particular json parameter.

例如,给定以下json数据:

For example, given the following json data:

{
  type: "type1",
  type1data: "type1value"
}

{
  type: "type2",
  type2data: "type2value"
}

我希望能够对ApiController进行2种不同的操作:

I'd like to be able to have 2 different actions on my ApiController:

void CreateType1(string type1data) 
{ 
  // ... 
}

void CreateType2(string type2data) 
{ 
  //... 
}

如何完成这样的事情?

更新:

如果可能,我想使用相同的URL.类似于/objects/create.

I'd like the same URL if possible. Something like /objects/create.

推荐答案

我宁愿使用自定义的ApiControllerActionSelector.

I'd much rather use a custom ApiControllerActionSelector.

public class MyActionSelector : ApiControllerActionSelector
{
    public override HttpActionDescriptor SelectAction(
                                HttpControllerContext context)
    {
        HttpMessageContent requestContent = new HttpMessageContent(
                                                           context.Request);
        var json = requestContent.HttpRequestMessage.Content
                                .ReadAsStringAsync().Result;
        string type = (string)JObject.Parse(json)["type"];

        var actionMethod = context.ControllerDescriptor.ControllerType
            .GetMethods(BindingFlags.Instance | BindingFlags.Public)
            .FirstOrDefault(m => m.Name == "Create" + type);

        if (actionMethod != null)
        {
            return new ReflectedHttpActionDescriptor(
                               context.ControllerDescriptor, actionMethod);
        }

        return base.SelectAction(context);
    }
}

这是模型.我给它起了一个奇怪的名字Abc.

Here is the model. I gave it a weird name of Abc.

public class Abc
{
    public string Type { get; set; }
    public string Type1Data { get; set; }
}

这是操作方法.

public void Createtype1(Abc a)
{

}

最后,插入动作选择器.

Finally, plug-in the action selector.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Services.Replace(typeof(IHttpActionSelector),
                                    new MyActionSelector());
    }
}

如果您现在发布到http://localhost:port/api/yourapicontroller,则根据JSON中type字段中的值,将选择操作方法Create *.

If you now POST to http://localhost:port/api/yourapicontroller, depending on the value in type field in JSON, the action method Create* will be selected.

这篇关于根据json值路由到不同的动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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