传递参数为空

时间:2012-11-09 10:59:53

标签: asp.net-mvc asp.net-web-api

我正在尝试从MVC的默认成员资格中删除用户,但传递的参数始终为null。我使用了[HttpDelete]属性和[FromBody],但它提供了“500服务器内部错误”。下面是我的代码

    // Delete api/Del/user name

    public HttpResponseMessage DeleteUser(string user)
    {

        try
        {
            System.Web.Security.Membership.DeleteUser(user);
        }
        catch (Exception)
        {

            return Request.CreateResponse(HttpStatusCode.NotFound);
        }


        return Request.CreateResponse(HttpStatusCode.OK);
    }

这是我的“删除”动词的调用方法。

http://localhost:3325/api/Del/haris2

我已经为路由创建了这个webapi类。我在Same控制器中有一个没有参数的Get方法。它的工作很好。

WebApiConfig.cs

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

namespace DatabaseService_WebAPI.App_Start
{
    public class WebApiConfig
    {
        public static void Configure(HttpConfiguration config)
        {
            // Filters
            config.Filters.Add(new QueryableAttribute());


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

        }
    }
}

1 个答案:

答案 0 :(得分:2)

问题是MVC将您的参数按名称映射。因此,有两种方法可以解决您的问题

  1. 将您的操作参数的名称更改为id,因为这就是您的映射路径所期望的内容。

    public ActionResult DeleteUser(string id)
    {
        ...
    }
    
  2. 更新您的路线以查找user参数,而不是ID。

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{user}",
        defaults: new { user = RouteParameter.Optional }
    );