2016-02-29 103 views
1

我是web API的新手。使用Visual Studio Community 2015.非常简单的测试代码。如何将字符串发布到Web API控制器?

WebApiConfig.cs:

  config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}" 
     ); 

检视:

 $.ajax({ 
      url: 'api/ClassingAlgorithm/', 
      type: 'POST', 
      data: { userWeightings: JSON.stringify('hello') } 
     }); 

控制器:

public class ClassingAlgorithmController : ApiController 
{ 
    [HttpPost] 
    public ClassingResult PostWeightings([FromBody]string userWeightings) 
    { 
     return null; 
    } 
} 

在控制器的方法, “userWeightings” 始终为空。为什么?

+0

我确实看过很多帖子,那些在Stackoverflow上。他们都说上述应该可以工作,但它不会。我花了8个小时尝试所有选项和可能性,但它不起作用。 –

+0

你可以将它更改为'data:{userWeightings:'hello'}'并尝试。我真的认为'Json.Stringify'是问题。只需检查铬网络选项卡...什么是张贴到服务器 – harishr

回答

0

更改您的ajax请求如下。

$.ajax({ 
     url: 'api/ClassingAlgorithm/', 
     type: 'POST', 
     contentType: "application/json", 
     data: JSON.stringify('hello') 
    }); 
+0

试过。不起作用。 –

+0

我在该方法中放入以下行: –

+0

string strReq = new System.IO.StreamReader(HttpContext.Current.Request.InputStream).ReadT oEnd(); –

0

我刚刚制定了解决方案:

工作代码已在$就调用以下:

data: JSON.stringify(userWeightings), 

的不工作的代码有

data: { userWeightings: JSON.stringify(userWeightings) }, 

但我不明白为什么。

相关问题