如何通过POST将原始数据发送到WebApi

时间:2018-05-29 22:55:17

标签: c# asp.net-mvc asp.net-web-api

我试图向外部webapi发送邮件" raw"数据。我可以成功地使用例如Postman,但是当我尝试在我的MVC应用程序中执行此操作时,我收到以下错误:指定的值没有':'分隔器。参数名称:header

这是我调用webapi的代码:

public UserCustom GetUserByToken(string pToken)
{
    ResponseLogin vRespuesta = new ResponseLogin();
    UserCarmocal vUsuarioFinal = null;

    string vApiKey = ConfigurationManager.AppSettings["ApiKey"];
    string vDirUser = ConfigurationManager.AppSettings["EndpointUsr"];
    WebRequest request = WebRequest.Create(vDirUser);

    request.Method = "POST";
    request.ContentType = "application/json; charset=utf-8";
    request.Headers.Add("ApiKey", vApiKey);

    string postData = pToken;

    //I THINK THE ERROR IS IN THE NEXT LINE:
    request.Headers.Add(postData);

    using (Stream s = request.GetResponse().GetResponseStream())
    {
        using (StreamReader sr = new StreamReader(s))
        {
            vRespuesta = new JavaScriptSerializer().Deserialize<ResponseLogin>(sr.ReadToEnd());
            if (vRespuesta.status == "success")
            { vUsuarioFinal.FirstName = "Test"; }
        }
    }

    return vUsuarioFinal;
}

1 个答案:

答案 0 :(得分:1)

将pToken变量写入请求流

PSUEDO CODE

    public UserCustom GetUserByToken(string pToken)
    {
        ResponseLogin vRespuesta = new ResponseLogin();
        UserCarmocal vUsuarioFinal = null;

        string vApiKey = ConfigurationManager.AppSettings["ApiKey"];
        string vDirUser = ConfigurationManager.AppSettings["EndpointUsr"];
        WebRequest request = WebRequest.Create(vDirUser);

        request.Method = "POST";
        request.ContentType = "application/json; charset=utf-8";
        request.Headers.Add("ApiKey", vApiKey);

        var bytes = System.Text.Encoding.UTF8.GetBytes(pToken);

        var stream = request.GetRequestStream();
        stream.Write(bytes, 0, bytes.Length);
        stream.Flush();

        using (Stream s = request.GetResponse().GetResponseStream())
        {
            using (StreamReader sr = new StreamReader(s))
            {
                vRespuesta = new JavaScriptSerializer().Deserialize<ResponseLogin>(sr.ReadToEnd());
                if (vRespuesta.status == "success")
                { vUsuarioFinal.FirstName = "Test"; }
            }
        }

        return vUsuarioFinal;
    }