C# Web api post 参数始终为空

标签 c# web-services

我正在使用 token 在 C# 中做一个 Web API,但我需要接收 postman 的参数到我的方法

 [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

这是我的启动类,里面有所有的配置

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

最佳答案

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

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

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

关于C# Web api post 参数始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42866443/

相关文章:

python - 使用 Python 向 API Prestashop 发送请求

java - Android 中的异常 "Illegal character in query at index -"

vba - 在 Excel 中调用 Web 服务

c# - 合并 Entity Framework 中的迁移条目

c# - ClickOnce 开始菜单图标

c# - 从 iCloud 打开自定义文件到 Xamarin.iOS 应用程序不起作用

java - 在运行时启用/禁用 Spring-ws

java - 如何在 Axis2 WebService 中通过用户名和密码进行身份验证?

c# - 如何根据传递给 ASP.NET MVC 中的 Controller /操作的属性值有条件地绑定(bind)到 ninject?

c# - 具有 UI 自动化和 .net 的数据网格内容