简体   繁体   中英

how to send multipart/form-data in web services that c#?

how to read multipart/form-data in web services? i am send data using postman body form-data but postman is getting error.

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

error System.InvalidOperationException: Request format is invalid: multipart/form-data; boundary=----WebKitFormBoundary79Ky1A1Kfyyy7qUi. at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

that error have getting by postman.

enter image description here

Asmx file can also be used for rest api creation (Which is not the recommended approach).

This can be achieved by the below code snippet.

[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);
    }
}

You can test this code in c# with the code that is shown below:

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM