首页 新闻 会员 周边

MVC4 项目下Web API 路由配置问题

0
悬赏园豆:10 [待解决问题]

项目是MVC4项目,然后想用里面的web api 的东西,于是乎就在 WebApiConfig 中做了如下配置

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

,然后在 项目根目录下的Controllers文件夹中新增 FileUpLoadController ,定义的Action 如下代码:

public class FileUpLoadController : ApiController
{
    [HttpPost]
        public Task<UpLoadBaseResponse> Post(){}
     [HttpGet]
        public ListImageResponse GetFileList(string imgListPath, string imgAllowFiles){}
}

项目调试中发现 使用 url:http://localhost:55759/api/FileUpLoad/GetFileList?imgListPath=news访问不到action。经过测试发现是 因为 GetFileList 必须传递2个参数才行,但是实际使用中,有时用不到的参数是不传的。那么问题来了:我的路由 应该怎么配置才能让action接受任意数量的参数 ?

BoyLife的主页 BoyLife | 初学一级 | 园豆:18
提问于:2015-11-26 10:01
< >
分享
所有回答(3)
0

public ListImageResponse GetFileList(string imgListPath, string imgAllowFiles = string.Empty) 试试

xiezhenhao | 园豆:100 (初学一级) | 2015-11-26 10:23
0

1、首先你应该先添加一个区域api

2、在区域中添加控制器FileUpLoad

3、然后写方法

4、测试

凝冰 | 园豆:685 (小虾三级) | 2015-11-26 10:57

如果说要多个参数的话可以传入对象,然后需要多少个参数在对象中加上就可以了。没有传入的话,对象会有个默认值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace mvcWeb.Areas.api.Controllers
{
    public class FileUpLoadController : Controller
    {
        //
        // GET: /api/FileUpLoad/

        public string GetFileList(DemoModel model)
        {
            return model.imgListPath;
        }

    }

    public class DemoModel
    {
        public string Parm1 { get; set; }
        public string imgListPath { get; set; }
    }
}
支持(0) 反对(0) 凝冰 | 园豆:685 (小虾三级) | 2015-11-26 11:07

你这个 Controller 为啥不是 继承 的 ApiController

支持(0) 反对(0) BoyLife | 园豆:18 (初学一级) | 2015-12-09 11:46

@BoyLife: 这个是一般的controller

支持(0) 反对(0) 凝冰 | 园豆:685 (小虾三级) | 2015-12-09 12:25
0

可空参数或者有默认值参数

吴瑞祥 | 园豆:29449 (高人七级) | 2015-11-26 11:26
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册