加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 如何使用WebApi将POSTHttpRoute POST到自定义操作?

发布时间:2020-12-16 07:28:44 所属栏目:asp.Net 来源:网络整理
导读:我试图弄清楚Web API路由背后的疯狂. 当我尝试发布这样的数据时: curl -v -d "test" http://localhost:8088/services/SendData 我收到404,并出现以下错误消息: {"Message":"No HTTP resource was found that matches the request URI 'http://localhost:80
我试图弄清楚Web API路由背后的疯狂.

当我尝试发布这样的数据时:

curl -v -d "test" http://localhost:8088/services/SendData

我收到404,并出现以下错误消息:

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:8088/services/SendData'.","MessageDetail":"No action was found on the controller 'Test' that matches the request."}

这是我的测试服务器的代码.

public class TestController : ApiController
{

    [HttpPost]
    public void SendData(string data)
    {
        Console.WriteLine(data);
    }
}

class Program
{
    static void Main(string[] args)
    {

        var config = new HttpSelfHostConfiguration("http://localhost:8088");

        config.Routes.MapHttpRoute(
            name: "API Default",routeTemplate:"services/SendData",defaults: new { controller = "Test",action = "SendData"},constraints: null);

        using (var server = new HttpSelfHostServer(config))
        {
            server.OpenAsync().Wait();  
            Console.WriteLine("Press Enter to quit.");
            Console.ReadLine();
        }

    }
}

更一般地说,为什么ASP.NET团队决定使MapHttpRoute方法如此混乱.为什么需要两个匿名对象….如何知道这些对象实际需要哪些属性?

MSDN没有提供任何帮助:http://msdn.microsoft.com/en-us/library/hh835483(v=vs.108).aspx

如果你问我,动态类型语言的所有痛苦都没有任何好处……

解决方法

使用此签名,它将每次都有效.

public class TestController : ApiController
{
    [HttpPost]
    [ActionName("SendData")]
    public HttpResponseMessage SendData(HttpRequestMessage request)
    {
        var data = request.Content.ReadAsStringAsync().Result;
        Console.WriteLine(data);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读