0

我正在.Net 中编写一个身份验证提供程序作为 REST 服务,以便更轻松地从 PHP 和 iOS 调用。我使用了 MVC Web API 库,一切正常,我可以从浏览器等调用方法。

但是当我尝试使用curl -d "something=something" hxxp://myendpoint/api从 cURL 调用我的 POST 方法时,使用-d在消息正文中传递的数据不会被解释为匹配我的 Web API 类中的方法,我看不到如何访问此表单类型字段。

我无法更改 curl 调用,因为它来自 3rd-party 库并且似乎是正确的,但是尽管我了解 Web API 的设计仅将 uri 参数与操作匹配,但我不明白为什么我无法访问表单来自请求对象的数据(或者我可以?)

[HttpPost] public AccessToken Post() {} // Matches but can't access form data
[HttpPost] public AccessToken Post2(string something) {} // Doesn't match, no parameter in curl uri querystring
[HttpPost] public AccessToken Post3(ModelWithOnePropertyCalledSomething data) {} //Matches but can't access form data

这真的是 Web API 无法实现的吗?我必须编写自定义动作选择器类吗?

4

2 回答 2

0

This is what I use for manipulating cURL in PHP:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "http://url/"); 
curl_setopt($ch, CURLOPT_USERAGENT, "Useragent"); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml; charset=UTF-8')); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_USERPWD, "username:password"); 
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); 
curl_setopt($ch, CURLOPT_POSTFIELDS, "postdata"); 
$data = curl_exec($ch); 
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE); 

I understand that you might not be able to modify the PHP code, but if you have access to a server with PHP, you could try this code to see if anything returns from your ASP.NET MVC 3 authentication service. Then make the appropriate edits in your .NET code to make it play nice in PHP.

Here's some example ASP.NET MVC 3 code:

[HttpGet]
public ActionResult SomeAction(string someParam)
{
   return View();
}

You will need to edit your routing definitions in your Global.asax.cs code to accept querystring-less urls. For example you could setup a route like this:

routes.MapRoute(
            "API/SomeAction/SomeParam",
            "api/someaction/{someParam}",
            new { controller = "API", action = "SomeAction" }
            );

As far as processing post data from cURL, you'll need to see the content type that is being sent from cURL and handle the data appropriately.

于 2013-03-28T19:39:23.930 回答
0

我找到了我需要的东西,它是这样的:

[HttpPost]
    public AccessToken Post2()
    {
        var data = Request.Content.ReadAsFormDataAsync();
        data.Wait();
        var form = data.Result;

        return new AccessToken() { Value = "" };
    }

基本上,请求和显然所有的 web api 框架都是异步的,这很好,但它需要更多的代码行才能使其工作。我猜我需要等待数据,因为 ReadAsFormDataAsync 在我到达下一行代码时可能还没有完成。我还需要检查发布的类型等,以避免出现我不想要的异常。

于 2013-04-02T10:25:12.637 回答