как отправить Content-Disposition: форма-данные;name = "name" правильно, когда вызываете post api из C #, чтобы избежать statuserror 500 - PullRequest
0 голосов
/ 26 февраля 2019
public async Task<T> PostFrom<T>(string baseAddress, string url, string requestbody)
{
    T obj = default(T);
    //Create the Uri string
    string request = baseAddress + url;
    WriteLog(request + " : " + "start");
    try
    {
        //Create the Uri
        var urirequest = new Uri(request);
        //define MultipartFormDataContent
        var multipart = new MultipartFormDataContent();

        //Add Content-Type
        multipart.Headers.Remove("Content-Type");
        multipart.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + financialAuth.Value.ContentType.boundary);
        //Add AuthToken
        multipart.Headers.Add("AuthToken", financialAuth.Value.AuthToken);

        //start adding the Content-Disposition which i have 3 of them
        //1st Content-Disposition form-data; name="SearchCriteria" "requestbody" is the json
        if (!string.IsNullOrEmpty(requestbody))
        {
            var requestbodyContent = new StringContent(JsonConvert.SerializeObject(requestbody));
            requestbodyContent.Headers.Add("Content-Disposition", "form-data; name=\"SearchCriteria\"");
            multipart.Add(requestbodyContent, "SearchCriteria");
        }
        //2nd Content-Disposition form-data; name="Secret" "financialAuth.Value.Secret" is the string
        var secretContent = new StringContent(financialAuth.Value.Secret);
        secretContent.Headers.Add("Content-Disposition", "form-data; name=\"Secret\"");
        multipart.Add(secretContent, "Secret");

        //3rd Content-Disposition form-data; name="AppID" "financialAuth.Value.AppID" is the string
        var appIdContent = new StringContent(financialAuth.Value.AppID);
        appIdContent.Headers.Add("Content-Disposition", "form-data; name=\"AppID\"");
        multipart.Add(appIdContent, "AppID");
        //define the HttpRequestMessage of type post 
        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, urirequest);

        //assign the multipart of httpRequestMessage.Content
        httpRequestMessage.Content = multipart;

        //assign the urirequest of httpClient.BaseAddress
        client.BaseAddress = urirequest;
        WriteLog("start url" + request);

        /* Here when I call the post web api I'm getting below error:
        {{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent,
        Headers: { 
            Cache-Control: no-cache 
            Pragma: no-cache 
            Server: Microsoft-IIS/8.5 
            X-AspNet-Version: 4.0.30319 
            Access-Control-Allow-Origin: * 
            Access-Control-Allow-Headers: Content-Type,authtoken
            Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS 
            Date: Tue, 26 Feb 2019 14:59:51 GMT 
            Content-Type: application/json; charset=utf-8 
            Expires: -1 
            Content-Length: 36
        }}
        */

        HttpResponseMessage response = await client.SendAsync(httpRequestMessage).ConfigureAwait(false);
        WriteLog("END url" + request);

        if (response.IsSuccessStatusCode)
        {
            WriteLog(request + " : " + "Begin Result");
            string result = await response.Content.ReadAsStringAsync();
            obj = JsonConvert.DeserializeObject<T>(result);
            WriteLog(request + " : " + "End Result");
        }
    }
    catch (Exception ex)
    {
        WriteLog(request + "  " + ex.Message);
    }
    return obj;
}

1 Ответ

0 голосов
/ 01 марта 2019

Я только что решил ошибку, прокомментировав следующий код:

// Add Content-Type
multipart.Headers.Remove("Content-Type");
multipart.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + financialAuth.Value.ContentType.boundary);

Кажется, тип контента будет создан автоматически MultipartFormDataContent.

Спасибо, что заглянули в мою проблему.

...