2017-03-17 36 views
1

我做的在C#與令牌的網絡API,但我需要接受郵遞員的參數,以我的方法C#的Web API之後的參數總是空

[HttpPost, Route("api/cobro/saveEmail")] 
    public IHttpActionResult SaveEmailForDiscount([FromBody] string email) 
    { 
     //do something with e-mail 
     return Ok(email); 
    } 

但總是電子郵件是空

這是郵遞員要求

POST /api/cobro/saveEmail HTTP/1.1 
Host: localhost:53107 
Content-Type: application/x-www-form-urlencoded 
Cache-Control: no-cache 
Postman-Token: 881045b2-0f08-56ac-d345-ffe2f8f87f5e 

email=jose%40gm.com 

這是我的啓動類是在那裏所有的配置

using System; 
using Microsoft.Owin; 
using Owin; 
using Microsoft.Owin.Security.OAuth; 
using System.Web.Http; 
using System.Net.Http.Headers; 

[assembly: OwinStartup(typeof(Cobros_BackEnd.Startup))] 

namespace Cobros_BackEnd 
{ 
    public class Startup 
    { 
     public void Configuration(IAppBuilder app) 
     { 


    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); 

     var MyProvider = new AuthorizationServerProvider(); 
     OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions 
     { 

      AllowInsecureHttp = true, 
      TokenEndpointPath = new PathString("/token"), 
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), 
      Provider = MyProvider 
     }; 
     app.UseOAuthAuthorizationServer(options); 
     app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); 

     HttpConfiguration config = new HttpConfiguration(); 
     config.Formatters.JsonFormatter.SupportedMediaTypes 
     .Add(new MediaTypeHeaderValue("text/xml")); 

     //get all users 
     config.Routes.MapHttpRoute(
      name: "Users", 
      routeTemplate: "api/{controller}/users", 
      defaults: new { id = RouteParameter.Optional } 
      ); 



     WebApiConfig.Register(config); 
    } 
    } 
} 

我使用GET其他方法和一切工作正常,但我需要在你的請求的主體使用本上POST

回答

2

,你可以創建一個這樣

public class SaveEmailModel{ 
    public string Email{get;set;} 
} 

public IHttpActionResult SaveEmailForDiscount([FromBody] SaveEmailModel model){ 
... 
} 
+0

這是解決這個問題的最簡單的方法IMO – victor

2

試試這個: =何塞%40gm.com

網絡API對於在帖子正文中傳遞的簡單類型不起作用。你需要實際實現一個自定義數據綁定器才能做到這一點。我剛纔說的是解決方法。我避免在Web API中以任何代價發佈簡單類型。編號傾向於創建一個模型對象,然後發送數據在JSON中映射到我的模型。你也可以使用[FromUri]並在url中傳遞你的字符串。

+0

你能舉一個例子或引用的類包裝電子郵件領域? – Heisenberg06

+0

http://stackoverflow.com/questions/19093603/simple-post-to-web-api – victor