如何在C#的Web服务中发送多部分/表单数据?

时间:2018-11-12 07:19:48

标签: c# asp.net postman

如何读取Web服务中的多部分/表单数据? 我使用邮递员的身体形式数据发送数据,但邮递员遇到错误。

    public class Api : System.Web.Services.WebService
    {
        [WebMethod(EnableSession = true)]
        [ScriptMethod(ResponseFormat=ResponseFormat.Json)]
        public string Hell(string name)
        {
            return CommonUtilities.GetJSonSerialized(name);
        }
    }
  

错误System.InvalidOperationException:请求格式无效:   多部分/表单数据; boundary = ---- WebKitFormBoundary79Ky1A1Kfyyy7qUi。   在System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()   在   System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

邮递员弄错了。

enter image description here

1 个答案:

答案 0 :(得分:0)

Asmx文件也可以用于创建REST API(不推荐使用这种方法)。

这可以通过以下代码段实现。

[ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class Randezvous : WebService
{
    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public void getUnitPersonels(string user, string pass, decimal unitNo)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        #region ..:: Kullanıcı şİfre Kontrol ::..
        if (!(unit == "xxx" && pass == "yyy"))
        {

            string msg = "User or pass is wrong.";
            Context.Response.Write(serializer.Serialize(msg));
            return;
        }
        #endregion

        List<Personels> personels = _units.getUnitPersonels(unitNo);

        string jsonString = serializer.Serialize(personels);
        Context.Response.Write(jsonString);
    }
}

您可以使用下面显示的代码在c#中测试此代码:

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var builder = new UriBuilder("http://localhost:18511/Randezvous.asmx/getUnitPersonels");
    var query = HttpUtility.ParseQueryString(builder.Query);
    query["unitNo"] = "0";
    builder.Query = query.ToString();
    string url = builder.ToString();

    var result = Task.FromResult(client.GetAsync(url).Result).Result.Content;
    var resultJson = result.ReadAsStringAsync().Result;

}