【问题标题】:C# Web api post parameter always nullC# Web api post 参数始终为空
【发布时间】:2017-08-09 12:54:27
【问题描述】:

我正在用令牌在 c# 中做一个 Web API,但我需要将邮递员的参数接收到我的方法中

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

但电子邮件始终为空

这是 PostMan 请求

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

这是我的 Startup 类,所有配置在哪里

    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 上使用它

【问题讨论】:

    标签: c# web-services


    【解决方案1】:

    您可以像这样创建一个类包装电子邮件字段

    public class SaveEmailModel{
        public string Email{get;set;}
    }
    
    public IHttpActionResult SaveEmailForDiscount([FromBody] SaveEmailModel model){
    ...
    }
    

    【讨论】:

    • 这是解决这个问题 IMO 最简单的方法
    【解决方案2】:

    在您的请求正文中尝试此操作: =jose%40gm.com

    Web Api 不能很好地处理在帖子正文中传递的简单类型。您需要实际实现一个自定义数据绑定器才能执行此操作。我刚刚提出的是一种解决方法。我避免在 Web api 中不惜一切代价在正文中发布简单类型。我更喜欢创建一个模型对象,然后以 JSON 格式发送数据,该数据将映射到我的模型。您还可以使用 [FromUri] 并在 url 中传递您的字符串。

    【讨论】:

    • 可以举个例子或者参考一下吗?
    猜你喜欢
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 2017-06-07
    • 2019-03-06
    • 1970-01-01
    相关资源
    最近更新 更多